简体   繁体   English

jQuery使用文档正文获取一致的宽度

[英]Jquery get consistent width using document body

I want to get the width of a web page and discovered that using $(window).width() doesn't return a consistent value due to the width of the scrollbar which varies depending on the browser and whether or not the scrollbar is visible. 我想获取网页的宽度,发现使用$(window).width()不会返回一致的值,这是因为滚动条的宽度随浏览器的不同以及滚动条是否可见而有所不同。

Instead of window I'm getting the width of the document body: 我得到的不是窗口,而是文档主体的宽度:

$('body').innerWidth()

It seems to return the correct value when testing. 测试时似乎返回正确的值。 Has anyone had any issues using this approach? 有没有人使用这种方法有任何问题?

Try setting body{width: 100%;} in css. 尝试在CSS中设置body {width:100%;}。 You may need to place that code in a $(document).ready(function(){}); 您可能需要将该代码放在$(document).ready(function(){});中。 callback or in a short timeout. 回调或短暂超时。 One problem with getting DOM elements sizes is that you can get the size before it's been calculated in its final state. 获取DOM元素大小的一个问题是,您可以在最终状态下计算出大小之前就获得它。 Even though it looks the correct width instantly there may be a few milliseconds where it hasn't been calculated. 即使立即看起来正确的宽度,也可能有几毫秒的时间尚未计算出来。 Takes a little playing around with. 需要一点玩耍。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM