javascript - 无法在 SVG 中获取 tspan 的宽度

标签 javascript jquery svg

对于 Firefox 和 Safari 中的 svg:text tspan 元素,宽度似乎始终为零(或 null)。

对于 Firefox 11 和 IE 9 中的 SVG tspan 文本元素,jQuery 函数 width() 和 height() 返回 0。 在 Chrome 17 和 19 中,它们都按预期工作。 我也试过 usinf offsetWidth 和 getComputedTextLength() 都返回 0 或 null。

这是我的查询代码:

$('svg #aitext-2-front-middle').find('tspan').each(function(i){                
   var currWidth = $(this).width();
   console.log(currWidth);
});

这是 svg 部分:

<text id="aitext-2-front-middle" transform="matrix(1 0 0 1 81.7744 155.248)">
    <tspan x="66.287" y="57.6" font-family="'MyriadPro-Regular'" font-size="12">lightweight UIs using </tspan>
    <tspan x="39.72" y="72" font-family="'MyriadPro-Regular'" font-size="12">Adobe Illustrator CS5 (or above) </tspan>
    <tspan x="40.146" y="86.4" font-family="'MyriadPro-Regular'" font-size="12">along with some free resources. </tspan>
    <tspan x="79.385" y="100.8" font-family="'MyriadPro-Regular'" font-size="12">Let’s get started.</tspan>
</text>

最佳答案

对您的代码稍作修改即可使其适用于:

  • Chrome (34)
  • 火狐 (28)
  • ie(ie10标准模式和模仿ie9)
  • Safari 5.1.7(Windows)

看看this demo看到它的工作。

使用

$(document).ready(function() {
    $('svg #aitext-2-front-middle').find('tspan').each(function(i, e){
       var currWidth;

       currWidth = $(this).width();
       if (!currWidth) {
           currWidth = e.getBoundingClientRect().width;
           if ((!currWidth) && (e.parentNode.getBBox)) {
               currWidth = e.parentNode.getBBox().width;
           }
       }

       console.log(currWidth);
    });
});

不幸的是,隐式浏览器开关似乎是必要的。特别是,tspan 元素在 ie 中没有 getBBox 方法,而 text 元素有。

编辑:

替代方法可能是调用 getComputedTextLength()(荣誉转到 here )。其输出已合并到现场演示中

关于javascript - 无法在 SVG 中获取 tspan 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23495756/

相关文章:

javascript - 在 JavaScript 中更改映射中的值和闭包中的引用

javascript - 使用 webpack 开发服务器将 javascript 入口点注入(inject)到 html 文件中?

javascript - moment.js 中的 isValid() 和 _isValid 有什么区别?

javascript - Bootstrap 日期时间选择器动态默认日期不起作用

css - Adobe Illustrator 删除了我在 svg 图像上的类名。我怎样才能防止这种情况发生?

javascript - 在一个数据绑定(bind)中应用 knockout if 和选项绑定(bind)在一起

javascript - 如何在 Scalajs 中使用 Ajax 上传文件

javascript - jquery UI datepicker 在传递日期之前触发输入模糊,避免/解决方法?

javascript - D3 : Invalid attribute [object Object]

xml - 在 cocos2d-x 中使用 xml