滚动嵌套在resize中

时间:2016-11-21 15:34:54

标签: javascript jquery

我写了一些jquery,我的目标是:

如果屏幕尺寸大于981,那么我想跟踪滚动事件并进行一些css更改。

如果屏幕尺寸小于981,那么我不想跟踪滚动事件,而只是应用一些css样式。

我想在调整大小的同时检查这个条件。

我的jquery代码如下所示,但问题是当我调整窗口大小并调整大小时,使其低于981宽度,然后滚动事件继续被跟踪,其中的内容将被执行。

        $(window).on("resize", function () {
var screenwidth = $(window).width();
if ( screenwidth > 981) {
    $(window).scroll(function()
{   
    var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();

    if ( wintop>100)
    {
        //always in view
                    console.log('test100');
        $('#slider-top-box').css({ "position":"relative","margin-top":"70px" });
                    $('#news-top-box').css({ "z-index":"1","margin-top":"-70px","background-color":"transparent","padding":"inherit" });
    }
    else
    {
                    $('#slider-top-box').css({ "position":"fixed","margin-top":"0px" });
                    $('#news-top-box').css({ "z-index":"1","margin-top":"0px","background-color":"transparent","padding-top":"380px" });
    }
});
} else {
    $('#slider-top-box').css({ "position":"relative","margin-top":"0px" });
    $('#news-top-box').css({ "padding-top":"50px" });
}}).resize();

1 个答案:

答案 0 :(得分:0)

在不希望跟踪事件处理程序时删除它。

$(window).off("scroll");声明中使用else

        $(window).on("resize", function () {
var screenwidth = $(window).width();
if ( screenwidth > 981) {
    $(window).scroll(function()
{   
    var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();

    if ( wintop>100)
    {
        //always in view
                    console.log('test100');
        $('#slider-top-box').css({ "position":"relative","margin-top":"70px" });
                    $('#news-top-box').css({ "z-index":"1","margin-top":"-70px","background-color":"transparent","padding":"inherit" });
    }
    else
    {
                    $('#slider-top-box').css({ "position":"fixed","margin-top":"0px" });
                    $('#news-top-box').css({ "z-index":"1","margin-top":"0px","background-color":"transparent","padding-top":"380px" });
    }
});
} else {
    $(window).off("scroll");
    $('#slider-top-box').css({ "position":"relative","margin-top":"0px" });
    $('#news-top-box').css({ "padding-top":"50px" });
}}).resize();