首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在SVG中获得tspan的宽度

无法在SVG中获得tspan的宽度
EN

Stack Overflow用户
提问于 2014-05-06 13:13:50
回答 1查看 1.6K关注 0票数 3

对于Firefox & Safari中的svg: tspan元素,宽度似乎总是为零(或null)。

对于Firefox11和IE9中的SVG文本元素,jQuery函数width()和height()返回0。在Chrome 17和19中,它们都按预期工作。我还尝试过usinf offsetWidth & getComputedTextLength()都返回0或null。

这是我的查询代码:

代码语言:javascript
复制
$('svg #aitext-2-front-middle').find('tspan').each(function(i){                
   var currWidth = $(this).width();
   console.log(currWidth);
});

这是svg部分:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2014-05-06 13:29:36

只要稍加修改代码,它就可以在以下方面工作:

  • 铬(34)
  • firefox (28)
  • Ie10标准模式和模仿ie9)
  • safari 5.1.7 (窗户)

看一看这个演示,看看它是否有效。

使用

代码语言:javascript
复制
$(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() (kudos 这里)。它的输出已经被整合到现场演示中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23495756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档