webkit browsers are getting elements.width() wrong

2019-05-04 09:29发布

问题:

I am trying to get the correct calculated width of an container. All the browsers are getting the calculated width correctly. (even IE) but surprisingly Chrome and webKit browsers are getting a wired number.

I am trying to get the total width of the <li> including its border and padding + its margin-right.

Then multiply that by the length of <li>'s to get the exact width needed to hold them

I tracked down the problem with the width calculation.

Can anyone tell me whats wrong.

Thanks

HTML

 <div id="videoTotorialTumbs">
    <a href="#" id="thumbLeftArrow" class="inActive"></a>
   <a href="#" id="thumbRightArrow"></a>
      <div id="horizontalBelt">
        <ul style="width: 1056px;">
            <li><a rel="video1" href="#"><img src="http://dummyimage.com/110x90.jpg">     <span>Upload images</span></a></li>
            <li><a rel="video2" href="#"><img src="http://dummyimage.com/110x90.jpg"><span>Choose Theme</span></a></li>

        </ul>
    </div>
</div>

JS

var videoContext = $("#horizontalBelt"),
 videoBeltUL = videoContext.find("ul"),
 videoBeltLI = videoContext.find("li"),
 videoLength = videoBeltLI.length,
 videoWidth  = parseInt(videoBeltLI.eq(0).outerWidth())+parseInt(videoBeltLI.eq(0).css("marginRight")),
 beltTotalWidth = videoLength*videoWidth,
       // js goes on....

beltTotalWidth has a different value in webKit.

回答1:

Are you calling this from

$(document).ready(...) ?

if so try using

$(window).load(...)



回答2:

If you don't want to wait for the window load event, you could run it on each image's load event instead. As Gaby said in a comment, if you know the image's dimensions, adding width properties to your images would allow you to run it earlier.