jQuery:如果其他滚动函数,则进行动画处理

jQuery: animate if else scroll function

本文关键字:动画 处理 函数 如果 其他 滚动 jQuery      更新时间:2023-09-26
我设置了一个滚动函数,因此当窗口滚动超过 50px 时,.header-wrapdiv 会从 140px 的高度动画化到

70px ,理想情况下应该发生的事情是当您从顶部向下滚动不到 50px 时,.header-wrapdiv 应该从 70px 向后动画化140px但这个函数似乎没有正常工作:
js小提琴:http://jsfiddle.net/ub8Rb/

.HTML:

<div class="header-wrap">hello</div>
<div class="scroll"></div>

.CSS:

.header-wrap {
    position: fixed;
    width: 100%;
    height: 140px;
    top: 0;
    left: 0;
    text-align: center;
    background-color: #999;
    z-index: 9999;
}
.scroll {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 4000px;
}

j查询:

$(document).scroll(function () {
    if (window.scrollY > 50) {
        $(".header-wrap").animate({
            height: "70px"
        }, 500);
    } else {
        $(".header-wrap").animate({
            height: "140px"
        }, 500);
    }
});

这个函数似乎没有像我上面描述的那样工作,并且没有根据窗口滚动的距离来对div 的高度进行动画处理。任何建议将不胜感激!

这个很流畅...

var go = true;
$(window).scroll(function() {
    if ($(this).scrollTop() > 50 && go) {
        $(".header-wrap").stop().animate({height:'70px'}, 500);
        go = false;
    } else if ($(this).scrollTop() < 50 && !go) {
        $(".header-wrap").stop().animate({height:'140px'}, 200);
        go = true;
    }
});

做了一个小提琴:http://jsfiddle.net/filever10/z5D4E/

这可能是动画冲突的问题,因为如果您缓慢滚动,您的示例就可以工作。设置触发器以确定何时/是否播放高度动画应纠正冲突。下面是此工作的示例:

http://jsfiddle.net/ub8Rb/18/

var sizeTrigger = 'tall'; 
$(document).scroll(function () { 
    console.log(window.scrollY);
    if (window.scrollY > 50 && sizeTrigger == 'tall') {        
        $(".header-wrap").animate({
            height: "70px"
        }, 500, function() { 
            sizeTrigger = 'small'; 
            console.log(sizeTrigger);
        }); 
    } else if (window.scrollY < 50 && sizeTrigger == 'small') {
        $(".header-wrap").animate({
            height: "140px"
        }, 500, function() { 
            sizeTrigger = 'tall';
            console.log(sizeTrigger);
        });
    }
});

向代码中添加一个stop()$(".header-wrap").stop().animate ,这将停止任何当前正在执行的动画。 下面是一个包含修改代码的 JSFiddle:>>>单击此处

<<<<div class="answers">

发生的情况是您的滚动函数将快速触发,尝试执行animate()函数,这会将它们添加到浏览器的内存中。如果等待的时间足够长,队列将到达末尾,并且动画将按预期工作。

简单的解决方案,在animate()前面添加stop(true, false)

原料药:http://api.jquery.com/stop/

如果要控制延迟,可以使用包装器函数来捕获重复的事件。

var headerwrap = $(".header-wrap"),
    delayedEvent = (function () {
        var timers = {};
        return function (callback, delay, id) {
            delay = delay || 500;
            id = id || "duplicated event";
            if (timers[id]) {
                clearTimeout(timers[id]);
            }
            timers[id] = setTimeout(callback, delay);
        };
    })();
$(document).scroll(function (ev) {
    delayedEvent(function () {
        var h = (window.scrollY > 50) ? 70 : 140;
        headerwrap.stop(true, false).animate({ height: h }, 500);
    }, 500, "scroll event");
});

小提琴:http://jsfiddle.net/tive/QskJm/