javascript - 使用 jQuery 选择 SVG 宽度?

标签 javascript jquery svg

我需要能够使用 jQuery 在 embed 元素内选择 svg 元素的宽度和高度。请注意,如果答案很重要,它必须位于嵌入元素内。

我试过这个作为测试,但它返回 undefined:

var width = $('embed:first').children("svg:first").attr("width");
alert(width);

稍后当我让它工作时,我将使用 .each,所以这只是为了测试。

一些谷歌搜索似乎表明 svg 不能以这种方式轻易选择。有人可以确切地解释该怎么做吗?如果我需要使用 jQuery SVG 插件,你能解释一下实现上述功能的用法吗,因为我无法从网站上的示例中获得。

更新:请注意,svg 嵌入到具有 src 属性的嵌入元素中:

<embed class="image" width="100%" height="100%"
               src="svgimage.svg"
                        ></embed>

最佳答案

只需下载 jquery.svg.js 并在 jQuery 之后使用脚本元素加载它:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src='/js/jquery.svg.js'></script>

获取 SVG 元素:

var svg   = document.querySelector('embed').getSVGDocument().documentElement;
var width = svg.getAttributeNS(null, 'width');
console.log(width);

要获取所有 embed,请改用 document.querySelectorAll('embed')

完整示例(必须在服务器/本地主机上运行,​​本地文件不起作用):

<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src='jquery.svg.js'></script>
  </head>
  <body>
    <embed src="circle1.svg" type="image/svg+xml">
    <embed src="circle2.svg" type="image/svg+xml">

    <script>
      (function () {
        var embeds, embed, i, onSvgLoaded;

        onSvgLoaded = function () {
          var $svg;

          $svg  = $( this.getSVGDocument().documentElement );
          width = $svg.attr('width');
          console.log('Width:', width);
        };

        embeds = document.querySelectorAll('embed');

        for (i=0; embed=embeds[i]; i++) {
          embed.addEventListener('load', onSvgLoaded);
        }

      })();
    </script>
  </body>
</html>

circle1.svg:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100">
  <circle cx="50" cy="50" r="50" fill="red"/>
</svg>

circle2.svg:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="200" height="200">
  <circle cx="100" cy="100" r="100" fill="red"/>
</svg>

关于javascript - 使用 jQuery 选择 SVG 宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8443292/

相关文章:

javascript - 尽管 super 调用, super 类属性仍未定义

javascript - 使用 ecmascript 6 将 javascript 文件导入另一个文件的语法是什么?

jquery - 如何让Jqgrid卡住列自动换行

javascript - 在 react 组件中每 1.5 秒更改/改组文本

javascript,循环字段和验证

javascript - 克隆一个 SVG 路径并将其放入另一个 SVG 中

javascript - 选择未在 Material 设计中呈现 - 意外标记 `<`

javascript - 如何使用 HTML5 canvas 获取正确的 base64 格式的图像数据

javascript - SVG 元素的动态动画在 IE 中不起作用

html - 为什么我不能在我的 svg 路径上添加边框?