简体   繁体   中英

Simple, cross-browser way to get the WHOLE page width in JavaScript, not just the viewport width?

I've seen lots of posts that talk about the getting width of the browser viewport, but what I want to find is essentially the width of the browser viewport if it were just wide enough to avoid a horizontal scrollbar.

I'm using the Prototype JS framework and have looked at various options using that and using pure JavaScript. For example:

  • $(document.body).getWidth() and document.body.clientWidth return the viewport width excluding margins.
  • document.documentElement.clientWidth and window.innerWidth return the viewport width including margins.

I've tried to be sneaky too: I absolutely-positioned a known-width DIV against the right-hand edge of the page (ie CSS right:0 ) with the intention of getting its left-edge position, but that actually gets aligned with the right-edge of the viewport.

The only thing I've found that works is to use JavaScript to scroll right until it won't scroll anymore (simply using scrollBy(1000000, 0) will usually be enough, but a while loop would obviously be more reliable), then get the horizontal scroll offset and add that to the viewport width. But I don't want to scroll the window: I want to inspect it somehow!

Any suggestions appreciated, even jQuery ones as at least then I can see how jQuery does it.


Here's a simple example showing that document.body.scrollWidth doesn't work:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<body onload="document.getElementById('sw').innerHTML = document.body.scrollWidth">
<p><code>document.body.scrollWidth</code> = <span id="sw"></span></p>
<div style="position:absolute;left:0;bottom:0;width:1980px;background-color:#ccc;padding:10px;">This DIV is 2000px wide including padding.</div>
</body>
</html>

The output of this should show that the width is 2000px, since that's the width of the widest part of the page. It doesn't.

what about

window.screen.width;

document.body.style.width = (window.screen.width - 15) + 'px';

window.screen.width - 15 is enough to avoid horizontal scroll-bar. 15 is vertical scrollbar width.

for width:

document.body.scrollWidth

for height:

document.body.scrollHeight

EDIT: for IE you'll have to specify position:relative for the body tag

Browsers don't treat html and body like ordinary elements. In particular many browsers are really buggy with respect to how they treat scrollWidth etc. on the body element. The only real solution is to wrap all your content in one huge div for the entire page and use that. Because the div is an ordinary element it isn't affected by the bugs that cause the weird behaviour for body and html.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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