2013-03-26 22 views
4

我正在網上產品的網站,我trigging滾動事件,在開始只有12個元素將被顯示,但在第八元素滾動到頂部滾動事件應該只運行一次,但當我向下滾動時,它正在運行,請幫助。 這裏是我的代碼:只有一個條件後,一旦運行jQuery的事件匹配

var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top; 
    $(window).on("scroll",function(){ 
     var scroll_top = $(window).scrollTop(); // current vertical position from the top 
     // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative 
     if (scroll_top > sticky_navigation_offset_top) 
     { 
      console.log("Hi"); 
     }  
    }); 
+0

只需刪除事件處理程序。 – 2013-03-26 12:37:29

+0

在啓動時放置了一個var trigger = true。 後先點擊使假, 基於它允許滾動或不 – Bhadra 2013-03-26 12:37:43

回答

3

呼叫unbind()解除綁定從對象的事件。

$(window).on("scroll",function(){ 
    var scroll_top = $(window).scrollTop(); // current vertical position from the top 
    // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative 
    if (scroll_top > sticky_navigation_offset_top) 
    { 
     console.log("Hi"); 
    }  
    $(this).unbind("scroll"); 
}); 
+0

你的代碼工作正常,但我想運行相同的事件時,下一個8元 代碼: '變種navigation_offset_top = $(」電棒-list li:nth-​​child(4)')。offset()。top; var navigation_offset_top1 = $('。prods-list li:nth-​​child(8)')。offset()。top; $(窗口)。在( 「滾動」,函數(){ VAR scroll_top = $(窗口).scrollTop();如果 (scroll_top> navigation_offset_top || scroll_top> navigation_offset_top1) { 的console.log(「喜「); $ (本).unbind( '滾動');} });' ,但它不工作..請一次檢查。 – 2013-03-26 13:29:31

0

後就可以完全取消綁定事件。

$(this).unbind("scroll);

4

使用on()off(),當滾動到達點右鍵取消綁定事件處理程序:

var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top; 

$(window).on("scroll", doScroll); 

function doScroll() { 
    var scroll_top = $(window).scrollTop(); 
    if (scroll_top > sticky_navigation_offset_top) { 
     console.log("Hi"); 
     $(window).off('scroll', doScroll); 
    } 
}); 
+0

這幫了我。感謝很多人@adeneo – breezy 2016-05-20 02:11:59

4

我想你需要的是。一是方法

$(window).one("scroll",function(){ 
    var scroll_top = $(window).scrollTop(); // current vertical position from the top 
    // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative 
    if (scroll_top > sticky_navigation_offset_top) 
    { 
     console.log("Hi"); 
    }  
}); 

您可以在這裏瞭解更多:http://api.jquery.com/one/

+0

一個不正確的方式:(..我想, – 2013-03-26 12:57:52

+0

有些答案解決問題了嗎?如果沒有嘗試把你的代碼[的jsfiddle(http://jsfiddle.net/)。 – tassiodias 2013-03-26 13:06:36

+3

'一個()'只能使用一次,所以你觸摸滾動條或鼠標滾輪第二,它觸發一次,並沒有更多的,所以它永遠不會在條件語句。很驚訝這有兩個upvotes? – adeneo 2013-03-26 13:18:11

-1
var thisHash = window.location.hash; 
jQuery(document).ready(function() { 

    if(window.location.hash) { 
     jQuery.fancybox(thisHash, { 
     padding: 20 
     // more API options 
     }); 
    } 

}); 

這甚至更好,因爲你不需要按鈕來觸發fancybox。 而之前的代碼我無法在fancybox中插入表單,因爲每次我在表單內單擊時,都會重新啓動fancybox。

相關問題