jQuery的:如何检测窗口的宽度?

我的页面上有一个滚动元素(带有jScrollPane jQuery插件)。 我想完成的是通过检测浏览器窗口的宽度来closures滚动窗口的方法。 我正在做一个响应式布局,我希望当浏览器低于一定的宽度时closures这个滚动function。 当刷新页面时,我可以使其工作,但是当我调整浏览器窗口的大小时,宽度值不会即时更新。

现在,如果我从一个宽度为1000px的窗口开始,然后resize到350px,滚动function将保留。 当浏览器宽度达到440px时,我希望滚动functionclosures。

这是我到目前为止的代码..

var windowsize = $(window).width(); $(window).resize(function() { var windowsize = $(window).width(); }); if (windowsize > 440) { //if the window is greater than 440px wide then turn on jScrollPane.. $('#pane1').jScrollPane({ scrollbarWidth:15, scrollbarMargin:52 }); } 

更改一个variables不会奇迹般地执行if块中的代码。 将通用代码放在一个函数中,然后绑定事件,并调用该函数:

 $(document).ready(function() { // Optimalisation: Store the references outside the event handler: var $window = $(window); var $pane = $('#pane1'); function checkWidth() { var windowsize = $window.width(); if (windowsize > 440) { //if the window is greater than 440px wide then turn on jScrollPane.. $pane.jScrollPane({ scrollbarWidth:15, scrollbarMargin:52 }); } } // Execute on load checkWidth(); // Bind event listener $(window).resize(checkWidth); }); 

把你的条件里面resizefunction:

 var windowsize = $(window).width(); $(window).resize(function() { windowsize = $(window).width(); if (windowsize > 440) { //if the window is greater than 440px wide then turn on jScrollPane.. $('#pane1').jScrollPane({ scrollbarWidth:15, scrollbarMargin:52 }); } }); 

当您调整页面大小时,我不知道这对您是否有用:

 $(window).resize(function() { if(screen.width == window.innerWidth){ alert("you are on normal page with 100% zoom"); } else if(screen.width > window.innerWidth){ alert("you have zoomed in the page ie more than 100%"); } else { alert("you have zoomed out ie less than 100%"); } }); 

下面是我在屏幕尺寸低于768px时隐藏了一些Id元素,并在768px以上显示。 它工作很好。

 var screensize= $( window ).width(); if(screensize<=768){ if($('#column-d0f6e77c699556473e4ff2967e9c0251').length>0) { $('#column-d0f6e77c699556473e4ff2967e9c0251').css('display','none'); } } else{ if($('#column-d0f6e77c699556473e4ff2967e9c0251').length>0) { $('#column-d0f6e77c699556473e4ff2967e9c0251').removeAttr( "style" ); } } changething = function(screensize){ if(screensize<=768){ if($('#column-d0f6e77c699556473e4ff2967e9c0251').length>0) { $('#column-d0f6e77c699556473e4ff2967e9c0251').css('display','none'); } } else{ if($('#column-d0f6e77c699556473e4ff2967e9c0251').length>0) { $('#column-d0f6e77c699556473e4ff2967e9c0251').removeAttr( "style" ); } } } $( window ).resize(function() { var screensize= $( window ).width(); changething(screensize); });