实时检测浏览器大小 – jQuery / JavaScript
是否有jQuery插件或使用直接JavaScript来检测浏览器大小的方式。
我更喜欢它的结果是’实时’,所以如果宽度或高度改变,结果也会改变。
JavaScript的
function jsUpdateSize(){ // Get the dimensions of the viewport var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; document.getElementById('jsWidth').innerHTML = width; // Display the width document.getElementById('jsHeight').innerHTML = height;// Display the height }; window.onload = jsUpdateSize; // When the page first loads window.onresize = jsUpdateSize; // When the browser changes size
jQuery的
function jqUpdateSize(){ // Get the dimensions of the viewport var width = $(window).width(); var height = $(window).height(); $('#jqWidth').html(width); // Display the width $('#jqHeight').html(height); // Display the height }; $(document).ready(jqUpdateSize); // When the page first loads $(window).resize(jqUpdateSize); // When the browser changes size
jsfiddle演示
编辑:更新了JavaScript代码以支持IE8及更早版本。
您可以使用
function onresize (){ var h = $(window).height(), w= $(window).width(); $('#resultboxid').html('height= ' + h + ' width: ' w); } $(window).resize(onresize ); onresize ();// first time;
HTML:
这应该返回可见区域:
document.body.offsetWidth document.body.offsetHeight
我想这总是等于浏览器大小?
在任何你想要的地方使用宽度和高度变量……当浏览器大小改变时,它也会改变变量值。
$(window).resize(function() { width = $(this).width()); height = $(this).height()); });
你的意思是像这样的window.innerHeight; window.innerWidth
window.innerHeight; window.innerWidth
$(window).height(); $(window).width()
$(window).height(); $(window).width()
您可以尝试在重新resize时添加偶数监听器
window.addEventListener('resize',CheckBrowserSize,false); function CheckBrowserSize() { var ResX= document.body.offsetHeight; var ResY= document.body.offsetWidth; }