jQuery:如何快速检测窗口宽度? [英] jQuery: How to detect window width on the fly?
问题描述
我的页面上有一个滚动元素(使用jScrollPane jQuery插件)。我想要实现的是通过检测浏览器窗口的宽度来关闭滚动窗口的方法。我正在做一个响应式布局,我希望在浏览器低于一定宽度时关闭此滚动功能。当我刷新页面时,我能够使它工作,但是当我调整浏览器窗口的大小时,宽度值不会立即更新。
I have a scrolling element on my page (with the jScrollPane jQuery plugin). What I want to accomplish is a way to turn off the scrolling window by detecting the width of the browser window. I am doing a responsive layout and I want this scrolling feature to be turned off when the browser is below a certain width. I am able to make it work when I refresh the page, but when I resize the browser window the width value does not update on the fly.
现在,如果我开始使用宽度为1000px的窗口,则调整大小为350px,滚动功能仍然存在。我希望一旦浏览器宽度达到440px就关闭滚动功能。
Right now if I start out with a window that is 1000px wide then resize to 350px the scroll feature remains. I want the scroll feature to shut off as soon as the browser width hits 440px.
这是我到目前为止的代码..
Here's the code I have so far..
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
});
}
推荐答案
更改变量不会神奇地执行中的代码,如果
-block。将公共代码放在一个函数中,然后绑定事件,并调用函数:
Changing a variable doesn't magically execute code within the if
-block. Place the common code in a function, then bind the event, and call the function:
$(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);
});
这篇关于jQuery:如何快速检测窗口宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!