javascript jQuery width() 函数在 Internet Explorer 9 中返回错误的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10170670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:54:11  来源:igfitidea点击:

jQuery width() function returns wrong value in Internet Explorer 9

javascriptjqueryhtmlcssinternet-explorer

提问by HP.

I used Easy Slider jQuery plugin before and never had problem until now. And the problem is strange. Check out this home page http://bit.ly/HKiWY6

我以前使用过 Easy Slider jQuery 插件,直到现在才遇到问题。而且这个问题很奇怪。查看此主页 http://bit.ly/HKiWY6

The page will pop an alert showing two values:

该页面将弹出一个警报,显示两个值:

$("#slider").width()

and

$("#slider3").width()

I already set the value for both in css. One is 710px and one is 700px.

我已经在 css 中为两者设置了值。一个是 710px,一个是 700px。

If you run in IE9, it shows the default value of $(window).width() instead for both, whatever the window or document width currently is. FF and Chrome returned correctly. Why is that?

如果您在 IE9 中运行,它会显示 $(window).width() 的默认值,而不是两者,无论当前的窗口或文档宽度是什么。FF 和 Chrome 正确返回。这是为什么?

回答by Phradion

Try the outerWidth, and make sure to wrap it in a windows.ready event listener to make sure all DOM element rendered properly before the width being computed

尝试外层宽度,并确保将其包装在 windows.ready 事件侦听器中,以确保在计算宽度之前正确呈现所有 DOM 元素

$("#slider3").outerWidth()

回答by Casey Foster

I've had problems with jQuery's width()/height()/offset().top/.left etc in the past when I used them before a certain event fully bubbled. See if setTimeout(function() { alert($('#slider').width()); }, 0);has any effect. It's a cheap nextTick() trick that might be just what you need.

过去,当我在某个事件完全冒泡之前使用 jQuery 的 width()/height()/offset().top/.left 等时,我遇到了问题。看看setTimeout(function() { alert($('#slider').width()); }, 0);有没有影响。这是一个廉价的 nextTick() 技巧,可能正是您所需要的。