最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is "ScrollWidth" property of a span not working on Chrome? - Stack Overflow

programmeradmin0浏览0评论

I have a span with some text inside it.

document.getElementById('span1').scrollWidth;

on firefox return '100' as the scrollWidth but Chrome returns only '0'. Does Chrome not support this 'scrollWidth' property? Any other browser which doesnt support the same?

Also what would be work around for this if I need to get the length of a sentence in pixels?(I keep populating 'span1' with sentences using 'innerHTML' property)

I have a span with some text inside it.

document.getElementById('span1').scrollWidth;

on firefox return '100' as the scrollWidth but Chrome returns only '0'. Does Chrome not support this 'scrollWidth' property? Any other browser which doesnt support the same?

Also what would be work around for this if I need to get the length of a sentence in pixels?(I keep populating 'span1' with sentences using 'innerHTML' property)

Share Improve this question asked Nov 5, 2012 at 5:16 Bhumi SinghalBhumi Singhal 8,30711 gold badges52 silver badges79 bronze badges 2
  • <span id="span1" style="display:block">Bhumika</span> this when accessed using document.getElementById('span1').scrollWidth; gives the plete width of the page. This is different than the behaviour at firefox which provides the width of "bhumika" as the span's scrollWidth. – Bhumi Singhal Commented Nov 5, 2012 at 6:03
  • Setting the display=block;visibility=hidden wont work if done manually ..in the least it didn't for me. – Bhumi Singhal Commented Nov 5, 2012 at 7:46
Add a ment  | 

1 Answer 1

Reset to default 3

There is a lot of difference in how Firefox and Chrome respond to css and js. [ff=Firefox, c=Chrome, sw= scrollWidth ]

Key points:

  1. sw works only when the element's display is not inline and none.
    ff sets the display to block by default while c sets it to inline. So you would not get sw in c. If you need the element to be hidden anyways just use:
    visibility:hidden without setting the display for both ff and c.
  2. If u have set the visibility in c, use style.width of the element instead of sc. This works.

If you still want to use sc on chrome also for a hidden span, you could use @AnthonyWJones answer on

Knowing how wide a text line will be in HTML for word wrap and other applications

Worked for IE7,8,9 , FF, Chrome.

发布评论

评论列表(0)

  1. 暂无评论