[英]Trying to animate a div when scrolling up a page
我試圖找出為什么當我向上滾動頁面時element2
不會縮小到300 px。 當我向下滾動時,它會增長,但是當我向上滾動時,它不會后退。 我也很好奇為什么在滾動區域中有時寬度會自己切換(例如延遲的反應)。
$(document).ready( function(){
var lastSCroll = 0;
$(window).on("scroll", function(){
var scrolled = $(window).scrollTop();
if(scrolled > 470 && scrolled <1150){
$(".element2").show("slow").css({"top" : scrolled + 30});
}
if( scrolled > 770 && scrolled < 1150 && scrolled > lastSCroll){
$(".element2").animate({"width" : "500px"})
}
if(scrolled > 770 && scrolled < 1150 && scrolled < lastSCroll){
$(".element2").animate({"width" : "300px"})
}
$(".display").html(scrolled + ": lastScroll--> " + lastSCroll)
lastSCroll = scrolled ;
});
HTML:
<body>
<div class="element">Test</div>
<div class="element2">TEST 2</div>
<div class="display"></div>
<div class="firstCont"></div>
<div class="secondCont"></div>
<div class="thirdCont"></div>
<div class="fourthCont">4th</div>
CSS:
*{
margin: 0;
padding: 0;
}
.firstCont{
height: 100vh;
background: pink;
}
.display{
position: fixed;
top: 0;
right: 0;
padding: .5em 1em;
background: rgba(120,0,0,0.3);
z-index: 5;
}
.secondCont{
height: 100vh;
background: hotpink;
}
.thirdCont{
height: 100vh;
background: seagreen;
}
.fourthCont{
height: 100vh;
background: skyblue;
}
.element{
position: absolute;
width: 300px;
background: blue;
height: 200px;
display: none;
}
.element2{
background: gold;
width: 300px;
height: 200px;
position: absolute;
display: none;
}
在animate()
stop()
之前添加stop()
似乎可以解決問題。 它可以防止動畫隊列增加並引起奇怪的行為。 https://jsfiddle.net/o9o7ogsz/2/
$(document).ready(function () {
var lastSCroll = 0;
$(window).on("scroll", function () {
var scrolled = $(window).scrollTop();
if (scrolled > 470 && scrolled < 1150) {
$(".element2").show("slow").css({
"top": scrolled + 30
});
}
if (scrolled > 770 && scrolled < 1150 && scrolled > lastSCroll) {
$(".element2").stop().animate({
"width": "500px"
})
}
if (scrolled > 770 && scrolled < 1150 && scrolled < lastSCroll) {
$(".element2").stop().animate({
"width": "300px"
})
}
$(".display").html(scrolled + ": lastScroll--> " + lastSCroll)
lastSCroll = scrolled;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.