【问题标题】:Unable to get width of <rect element of <svg无法获取 <svg 的 <rect 元素的宽度
【发布时间】:2017-06-03 16:59:14
【问题描述】:

我正在尝试访问最后一个"rect",以便获得它的宽度和高度。我尝试关注 jquery $(".highcharts-plot-background").width() 但我得到的答案都是 0。还尝试使用 $(".highcharts-plot-background")[0].width() 但随后出现以下错误

未捕获的类型错误:$(...).width() 不是函数。

我愿意接受建议。

<svg version="1.1" class="highcharts-root" xmlns="http://www.w3.org/2000/svg" width="710" viewBox="0 0 710 325" height="325">
  <desc>Created with Highcharts 5.0.0</desc>
  <defs>
    <clipPath id="highcharts-1">
      <rect x="0" y="0" width="636" height="238" fill="none"></rect>    </clipPath>
  </defs>
  <rect fill="#ffffff" class="highcharts-background" x="0" y="0" width="710" height="325" rx="0" ry="0"></rect>
  <rect fill="none" class="highcharts-plot-background" x="64" y="50" width="636" height="238" style="margin:0px;"></rect>
</svg>

【问题讨论】:

    标签: javascript jquery css highcharts typeerror


    【解决方案1】:

    使用attr("width") 代替width()。如果您一直在 css 中声明宽度,那么 width() 就可以了。

    请参阅下面的 sn-p。

    console.log($(".highcharts-plot-background").attr("width"));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <svg version="1.1" class="highcharts-root" xmlns="http://www.w3.org/2000/svg" width="710" viewBox="0 0 710 325" height="325">
      <desc>Created with Highcharts 5.0.0</desc>
      <defs>
        <clipPath id="highcharts-1">
          <rect x="0" y="0" width="636" height="238" fill="none"></rect>    </clipPath>
      </defs>
      <rect fill="#ffffff" class="highcharts-background" x="0" y="0" width="710" height="325" rx="0" ry="0"></rect>
      <rect fill="none" class="highcharts-plot-background" x="64" y="50" width="636" height="238" style="margin:0px;"></rect>
    </svg>

    【讨论】:

    • 非常感谢。我在想 jQuery 会处理这些事情。
    猜你喜欢
    • 2013-08-11
    • 2017-01-31
    • 2010-12-10
    • 2013-11-11
    • 1970-01-01
    • 2019-04-11
    • 2018-02-26
    • 1970-01-01
    • 2018-01-12
    相关资源
    最近更新 更多