jQuery:如何动态检测窗口宽度? [英] jQuery: How to detect window width on the fly?

查看:22
本文介绍了jQuery:如何动态检测窗口宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有一个滚动元素(使用 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.

现在,如果我从一个 1000 像素宽的窗口开始,然后将其调整为 350 像素,滚动功能仍然存在.我希望在浏览器宽度达到 440 像素时立即关闭滚动功能.

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

推荐答案

更改变量不会神奇地执行 if 块中的代码.将常用代码放在一个函数中,然后绑定事件,调用函数:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆