【问题标题】:Not able to get the width of tspan in SVG无法在 SVG 中获取 tspan 的宽度
【发布时间】:2014-05-06 13:13:50
【问题描述】:

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

jQuery 函数 width() 和 height() 在 Firefox 11 和 IE 9 中为 SVG tspan 文本元素返回 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 上写这个文本...
  • 感谢您的评论..是的,我使用的是 chrome 34.. 但是 chrome 运行良好,但我在使用 Firefox 和 safari 时遇到问题

标签: javascript jquery svg


【解决方案1】:

对您的代码稍作更正即可使其在以下应用中发挥作用:

  • 镀铬 (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)。其输出已纳入现场演示

【讨论】:

  • 您发布的所有内容都已在问题本身中得到解答。
  • @Archer 不,它没有 - 没有一个浏览器接近当前版本,根本没有提到 jquery 版本,也没有提到 js 代码 sn-p 所在的上下文用过。
  • 哪个版本的FF?你什么时候调用代码?您是否收到现场演示的错误?
  • @Pankaj 对,我已经纠正了这个问题并更新了现场演示。
  • 这根本不是一个糟糕的答案(尤其是 2014 年!):元素的 x 是其兄弟元素宽度的总和,getComputedTextLength() 将为我们提供宽度。考虑一下 Chromium 现在(6 年后)只修复了 getBBox 错误,以及for WebKit the bug still exists, bug report here
猜你喜欢
  • 2017-06-03
  • 2017-09-15
  • 2017-01-28
  • 2013-08-11
  • 2013-02-09
  • 1970-01-01
  • 2017-01-31
  • 2014-02-26
  • 2010-12-10
相关资源
最近更新 更多