2016-11-21 105 views
0

我已經寫了一些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(); 
+0

我創建了一個jsbin顯示此。而不是981我已經展示了一個更小的截止點481.要測試這個問題,1)使輸出尺寸更大的tahn 481,然後滾動。這裏滾動事件應該跟蹤。現在使輸出框寬度小於480.現在滾動不應被跟蹤,但它是。 https://jsbin.com/pabahad/edit?html,js,console,output – asanas

回答

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