防止滚动jquery脚本运行两次

时间:2013-09-20 11:53:17

标签: javascript jquery html css scrolltop

我是jquery的新手,并将以下代码放在一起,以便在设置向下滚动量后显示DIV。如果向上滚动,DIV会消失。可选地,一旦出现DIV,就会有一个关闭它的链接。这一切都按预期工作,除此之外我只希望脚本运行一次。目前,如果我向上滚动,黄色框会再次出现。如何确保盒子保持关闭状态?作为另一种选择,我可以整合cookie或localStorage吗?

非常感谢!拉斯。

使用Javascript:

$(function () {
    var target = $(".box");
    if ($(window).scrollTop() > 30) {
        target.hide();
    }
    $(window).scroll(function () {
        var pos = $(window).scrollTop();
        if (pos > 30) {
            target.stop(true, true).fadeIn('slow');
        } else {
            target.stop(true, true).fadeOut('slow');
        }
    });
    $('a.close').click(function () {
        $($(this).attr('href')).slideUp();
        return false;
    });
}); 

以下是我的代码的jsfiddle链接:jsfiddle link

3 个答案:

答案 0 :(得分:1)

您可以删除该类以确保该框保持removeClass()。或者在动画后直接$(".box").remove()。 您可以使用cookie存储此选项,但如果客户端删除了他的cookie,则会丢失。

答案 1 :(得分:0)

试试这个http://jsfiddle.net/AbwXu/4/

var notdisplayed=true;
$(function(){ 
    var target = $(".box");
    if($(window).scrollTop() > 30){
      target.hide();
    }
    $(window).scroll(function(){
        var pos = $(window).scrollTop();
        if(pos > 30  && notdisplayed){
            target.stop(true, true).fadeIn('slow');

        } else {
            target.stop(true, true).fadeOut('slow');
            notdisplayed=false;
        }
    });
    $('a.close').click(function() {
        $($(this).attr('href')).slideUp();
        notdisplayed=false;
        return false;
    });

答案 2 :(得分:0)

您可以从窗口中删除事件滚动,而localStorage可以执行以下操作:

$(function () {
    var target = $(".box");
    if ($(window).scrollTop() > 30) {
        target.hide();
    }
    $(window).scroll(function () {
        var pos = $(window).scrollTop();
        if (pos > 30) {
            target.stop(true, true).fadeIn('slow');
        } else {
            target.stop(true, true).fadeOut('slow');
        }
        if(localStorage['noNotification'] == 'true'){
            $(window).off('scroll');
        }
    });
    $('a.close').click(function () {
        $($(this).attr('href')).slideUp();
        $(window).off('scroll');
        localStorage['noNotification'] = 'true';
        return false;
    });

});

相关问题