我正在制作在线产品网站,我正在触发滚动事件,在启动时只会显示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");
}
});
答案 0 :(得分:5)
使用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);
}
});
答案 1 :(得分:4)
我认为您需要的是 .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/
答案 2 :(得分: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");
});
答案 3 :(得分:1)
完成后你可以取消绑定事件。
赞$(this).unbind("scroll);
答案 4 :(得分:-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。