当我向上滚动页面时,我试图找出为什么element2
不会缩减到300像素。当我向下滚动它增长但当我向上滚动时它不会收缩。我也很好奇为什么有时当我在滚动区域时(例如延迟反应),宽度会自动切换。
$(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;
}
答案 0 :(得分:1)
在stop()
之前添加animate()
似乎可以解决问题。它可以防止动画队列建立并导致奇怪的行为。
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;
});
});