【问题标题】:Error when assigning currentScale of SVG root element分配 SVG 根元素的 currentScale 时出错
【发布时间】:2012-05-24 17:05:40
【问题描述】:

我对 SVG 和 JavaScript 有疑问:

此代码按预期运行:

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

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

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);

但 currentScale 的实际值并没有改变。无论传递给 setAttribute 什么,它都保持为 1。

【问题讨论】:

  • 您是否正在清理width 参数?在使用 parseFloat 之前打印其值以检查除法是否适用。
  • 好吧,我检查了 typeof(parseFloat(width)/400),它的计算结果是“数字”。这还不够吗?

标签: javascript svg jquery-svg


【解决方案1】:

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

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

【讨论】:

  • 所以 SVGRoot.currentScale = value 毕竟是正确的。在第一次调用时,宽度参数确实是 NaN。当我过滤这种情况时,一切都很好。
猜你喜欢
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多