【问题标题】:how to get width and height from a svg div by js如何通过js从svg div中获取宽度和高度
【发布时间】:2015-10-21 05:37:57
【问题描述】:

html中有一个div如下:

<svg id="box" width="312" height="101"></svg>

我要获取svg标签的宽高:

var el = window.document.querySelector('#box');

但我无法通过el 获取宽度和高度,我该如何获取它们? 我使用 node.js 来运行脚本。整个代码是:

var jsdom = require('jsdom'),
content = '<svg id="box" width="300" height="120"></svg>';

jsdom.env({ features : { QuerySelector : true }, html : content,
      done : function(errors, window) {
      var w =  window.document.querySelector('#box').attr("width");
      console.log(w);
     }
});

【问题讨论】:

  • 你为什么不试试getElementById
  • @RobertLongson 是的,它做不到。
  • @dingo_d 此代码已在 jsdom.env() 中使用...
  • @RobertLongson TypeError: undefined is not a function...错误提示。

标签: javascript html svg


【解决方案1】:
var myelm = document.getElementById("box").getAttribute('width');

【讨论】:

    【解决方案2】:

    使用getBoundingClientRect(),即well-supported

    Element.getBoundingClientRect() 方法返回一个大小 元素及其相对于视口的位置。

    var node = document.getElementById("yourElement");
    var rect = node.getBoundingClientRect();
    
    console.log("width:" + rect.width );
    console.log("height:" + rect.height);
    

    【讨论】:

    • 如果重要,请注意在IE8及以下版本中,getBoundingClientRect()返回的DOMRect对象缺少高度和宽度属性
    猜你喜欢
    • 2012-12-15
    • 2013-05-04
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2019-12-26
    • 2011-09-25
    相关资源
    最近更新 更多