I'm trying to detect the browser's current size (width and 开发者_运维知识库height). I know it's super easy in jQuery with $(document).width and $(document).height
, but I don't want to add the size of the jQuery lib to the project, so I'd rather just use built in JavaScript. What would be the short and efficient way to do the same thing with JavaScript?
// first get the size from the window
// if that didn't work, get it from the body
var size = {
width: window.innerWidth || document.body.clientWidth,
height: window.innerHeight || document.body.clientHeight
}
function getWindowSize(){
var d= document, root= d.documentElement, body= d.body;
var wid= window.innerWidth || root.clientWidth || body.clientWidth,
hi= window.innerHeight || root.clientHeight || body.clientHeight ;
return [wid,hi]
}
IE browsers are the only ones who don't use innerHeight and Width.
But there is no 'standard'- just browser implementations.
Test the html (document.documentElement) clientHeight before checking the body- if it is not 0, it is the height of the 'viewport' and the body.clientHeight is the height of the body- which can be larger or smaller than the window.
Backwards mode returns 0 for the root element and the window (viewport) height from the body.
Same with width.
Try this;
<script type="text/javascript">
winwidth=document.all?document.body.clientWidth:window.innerWidth;
winHeight=document.all?document.body.clientHeight:window.innerHeight;
alert(winwidth+","+winHeight);
</script>
Here is a code sample
function getSize(){
var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h=window.innerHeight || document.documentElement.clientHeight ||document.body.clientHeight;
}
My case use for window.innerWidth
involved building a custom modal pop up window. Simply put, the user clicks the button, the pop up opens centered in the browser and there is a transparent black bkgd behind the pop up. My issue was finding the width and height of the browser to create the transparent bkgd.
The window.innerWidth
works great to find the width but remember window.innerWidth and window.innerHeight
do not compensate for the scroll bars, so if your content goes beyond the visible content area. I had to subtract 17px from the value.
transBkgd.style.width = (window.innerWidth - 17) + "px";
Since the content of the site always went beyond the visible height I couldnt use window.innerHeight
. If the user scrolled down the transparent bkgd would end at that point and that just looked nasty. In order to maintain the transparent bkgd all the way to the bottom of the content I used document.body.clientHeight
.
transBkgd.style.height = document.body.clientHeight + "px";
I Tested the pop up in IE, FF, Chrome, and it looks good across the board. I know this doesnt follow the original question too much but I figure it might help if anyone else runs into the same issue when creating a custom modal pop up.
精彩评论