分配 SVG 根元素的当前比例时出错

Error when assigning currentScale of SVG root element

本文关键字:出错 SVG 元素 分配      更新时间:2023-09-26

我对SVG和JavaScript有问题:

此代码的行为符合预期:

function initSvg(width) {
    SVGRoot = document.getElementsByTagName('svg')[0];
    console.log(SVGRoot.currentScale);    // Displays '1' which is OK

但是当我尝试像这样重新分配当前缩放参数时:

function initSvg(width) {
    SVGRoot = document.getElementsByTagName('svg')[0];
    SVGRoot.currentScale = parseFloat(width)/400;   
    console.log(SVGRoot.currentScale);    // Should display some floating point number

我收到错误

Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) nsIDOMSVGSVGElement.currentScale]

并且不会执行警报。我分配到SVGRoot.currentScale有什么问题?

更新:

使用时错误消失

SVGRoot.setAttribute('currentScale', parseFloat(width)/400);

SVGRoot.setAttributeNS(null, 'currentScale', parseFloat(width)/400);

但当前刻度的实际值不会改变。无论传递到setAttribute的内容如何,它都保持在1。

setAttribute(NS) 的方式不正确,SVG 中没有 'currentScale' 属性。

"currentScale"是SVGSVGElement接口中的一个属性,只要数字合理(例如不是Inf或NaN),你应该能够像你一样获取和设置它。但请注意,SVG 1.1 规范仅定义了 currentScale 在最外层的 svg 元素上的行为。