4

我正在制作在线产品网站,我正在触发一个滚动事件,开始时只会显示 12 个元素,但是当第 8 个元素滚动到顶部时,滚动事件应该只运行一次,但每次向下滚动时它都会运行,请帮忙. 这是我的代码:

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

5 回答 5

6

当滚动到正确的点时,使用on()and和取消绑定事件处理程序: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);
    }
};
于 2013-03-26T12:39:47.473 回答
4

调用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");
});
于 2013-03-26T12:37:10.813 回答
3

我认为您需要的是.one方法

$(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/

于 2013-03-26T12:41:06.323 回答
1

您可以在完成后取消绑定事件。

喜欢 $(this).unbind("scroll);

于 2013-03-26T12:37:40.707 回答
-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。

于 2015-04-29T00:08:20.800 回答