JQuery: 如何动态检测窗口宽度?

我的页面上有一个滚动元素(使用 jScrollPane jQuery 插件)。我想要做的是通过检测浏览器窗口的宽度来关闭滚动窗口。我正在做一个响应布局,我希望这个滚动功能被关闭时,浏览器低于一定的宽度。我能够使它工作时,我刷新页面,但当我调整浏览器窗口的宽度值不会更新动态。

现在,如果我开始一个窗口是1000px 宽,然后调整到350px 滚动功能仍然存在。当浏览器的宽度达到440px 的时候,我希望关闭滚动功能。

这是我目前的代码。

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
});
}
232604 次浏览

将 if 条件放在 resize函数中:

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
});
}
});

更改变量并不能神奇地执行 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);
});

我不知道这对你调整页面大小是否有用:

$(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 i.e more than 100%");
} else {
alert("you have zoomed out i.e 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);
});