我正在尝试在页面滚动时制作动画,其中所选元素将在向下滚动时从左到右设置动画,如果返回顶部则从右到左(默认位置)设置所选元素的动画,这是我尝试过的
$(document).ready(function() {
$(window).scroll(function() {
var wS = $(this).scrollTop();
if (wS <= 10) {
$("#test-box").animate({
'left': 100
}, 500);
}
if (wS > 11) {
$("#test-box").animate({
'left': $('#main-container').width() - 100
}, 500);
}
});
});
#main-container {
width: 100%;
overflow: auto;
height: 500px;
}
#test-box {
background: red;
color: #ffffff;
padding: 15px;
font-size: 18px;
position: fixed;
left: 100;
top: 10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="test-box">test</div>
</div>
如您所见,向下滚动时,测试框会按照我的指示移动,但向上滚动时,默认情况下它不会向左移动,有什么想法吗?
最佳答案
您可以添加一个全局变量来控制动画。请看下面的工作片段,我在其中评论了我添加的部分代码:
$(document).ready(function() {
var animated = false; //added variable to control the animation
$(window).scroll(function() {
var wS = $(this).scrollTop();
if (animated && wS <= 10) {
$("#test-box").animate({
'left': 100
}, 500);
animated = false; //animation ended
}
if (!animated && wS > 11) {
$("#test-box").animate({
'left': $('#main-container').width() - 100
}, 500);
animated = true; //it was animated
}
});
});
#main-container {
width: 100%;
overflow: auto;
height: 500px;
}
#test-box {
background: red;
color: #ffffff;
padding: 15px;
font-size: 18px;
position: fixed;
left: 100px;
top: 10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="test-box">test</div>
</div>
关于javascript - 向下滚动时向右动画,向上滚动时向左动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42575394/