浏览器使用jquery调整大小后重置变量 [英] reset variables after browser resized using jquery

查看:59
本文介绍了浏览器使用jquery调整大小后重置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个jquery函数,可以在准备就绪和调整浏览器窗口时调用它。

I'm trying to create a jquery function that can be called both on ready and when the browser window is resized.

jQuery(document).ready(function($) {

function setWidth() {
    var windowWidth = $(window).width();
    var boxWidth = $('#addbox').width();
    var paddingWidth = (windowWidth - boxWidth) / 2;
};

$(setWidth);

$(window).resize(setWidth);

$(".scroll").click(function(event){     
    event.preventDefault();
    $('html,body').animate({scrollLeft:$(this.hash).offset().left-paddingWidth}, 750);
});

});

但该代码似乎不起作用,firebug说paddingWidth没有定义。我做错了什么?

But that code doesn't seem to be working, firebug says that paddingWidth isn't defined. What am I doing wrong?

推荐答案

变量具有定义它们的范围(使用 var )。在您的情况下,这意味着它们仅在 setWidth 中定义,并在每次执行该方法时重新初始化。

Variables have the scope in which they were defined (using var). In your case, this means that they are only defined within setWidth, and are re-initialised on each execution of that method.

您应该将它们移动到包含范围内,以便后代范围内的函数可以访问它们的值。

You should move them into a containing scope so that functions in descendant scopes have access to their values.

jQuery(document).ready(function ($) {
    var windowWidth, boxWidth, paddingWidth; // declare variables in this scope

    function setWidth() {
        windowWidth = $(window).width(); // set variables in this scope
        boxWidth = $('#addbox').width();
        paddingWidth = (windowWidth - boxWidth) / 2;
    };

    setWidth(); // just call the function

    $(window).resize(setWidth);

    $(".scroll").click(function (event) {
        event.preventDefault();
        $('html,body').animate({
            scrollLeft: $(this.hash).offset().left - paddingWidth
        }, 750);
    });
});

请注意 $(setWidth)是一个奇怪的电话,相对​​昂贵的电话。它说文件准备就绪时调用 setWidth 。由于您使用的是 jQuery(document).ready 处理程序,因此您可以确定这是真的。您只需使用 setWidth()执行该功能。

Note that $(setWidth) is an odd call, and a relatively expensive one. It says "call setWidth when the document is ready". Since you are in a jQuery(document).ready handler, you can be sure that that is true. You can just execute the function with setWidth().

这篇关于浏览器使用jquery调整大小后重置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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