简体   繁体   English

Javascript-获取文档宽度

[英]Javascript - Getting document width

I'd like to get the document's width with javascript (jQuery available), which I could achieve simply with document.width . 我想使用javascript(可使用jQuery)获取文档的宽度,只需使用document.width即可实现。 The problem comes up when the contents are positioned with a negative value, because document.width will retrieve the width less that value (you can see this behavior in http://jsfiddle.net/McgzK/1/ ). 当内容放置为负值时会出现问题,因为document.width将检索小于该值的宽度(您可以在http://jsfiddle.net/McgzK/1/中看到此行为)。 So, is there a way I can get the document's width straight forward, or should I do something like document.width - parseInt($(container).css('left')) ? 因此,有没有一种方法可以使文档的宽度直截了当,还是应该执行诸如document.width - parseInt($(container).css('left'))类的事情?

There is no straight forward way to get that width. 没有直接的方法来获得该宽度。 This width does not make any sense. 此宽度没有任何意义。 document.width is the value of documents width. document.width是文档宽度的值。 If you put something outside document layout its not included in documents width as its not in the document . 如果您将某些东西放在文档布局之外,则它不会包含在文档宽度中,而不会包含在文档 So for your Total width you have to add that portion. 因此,对于您的总宽度,您必须添加该部分。

Use the scrollWidth property of your element and add absolute left value of css position. 使用元素的scrollWidth属性,并添加css位置的绝对left值。

See http://jsfiddle.net/McgzK/11/ 参见http://jsfiddle.net/McgzK/11/

Note: 注意:

  1. if you want the width of content use scrollWidth property. 如果要内容的宽度,请使用scrollWidth属性。
  2. If you want to get the width of the element use offsetWidth . 如果要获取元素的宽度,请使用offsetWidth

尝试在CSS中将主体宽度设置为100%,然后使用jQuery获取主体的宽度,而不是文档的宽度。

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

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