admin管理员组

文章数量:1427168

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.

本文标签: javascriptIs quotScrollWidthquot property of a span not working on ChromeStack Overflow