我尝试使用 JQuery e.preventDefault();
来阻止滚动,但什么也没发生,我需要的是停止滚动,当动画 div 出现在屏幕右侧时,滚动必须工作:
$(document).ready(function () {
$(window).on('scroll', function (e) {
var animation = $(".my-container .animation"),
windowScroll = $(window).scrollTop();
if (parseInt(animation.css('left')) + animation.width() < $(window).width()) {
e.preventDefault();
animation.css('left', windowScroll * 1.5);
}
else {
// enable scroll
}
});
})
.my-container{
width:100%;
height:620px;
position:relative;
overflow:hidden;
background-color:#333333;
}
.my-container .animation{
position:absolute;
width:420px;
height:200px;
bottom:0;
left:0;
background-color:#02f15f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="my-container">
<div class="animation"></div>
</section>
请全屏运行代码片段
最佳答案
您必须使用 $(window).scrollTop(windowScroll);
e.preventDefault
来设置滚动条:
见下面的例子:
$(document).ready(function () {
var windowScroll = $(window).scrollTop();
$(window).on('scroll', function (e) {
var animation = $(".my-container .animation");
if (parseInt(animation.css('left')) + animation.width() < $(window).width()) {
var scrl = $(window).scrollTop();
$(window).scrollTop(windowScroll);
//console.log(parseInt(animation.css('left')));
animation.css('left', parseInt(animation.css('left')) + (scrl * 1.5));
}
else {
// enable scroll
}
});
})
body{
height:2000px;
}
.my-container{
width:100%;
height:400px;
position:relative;
overflow:hidden;
background-color:#333333;
}
.my-container .animation{
position:absolute;
width:420px;
height:200px;
bottom:0;
left:0;
background-color:#02f15f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="my-container">
<div class="animation"></div>
</section>
关于javascript - 防止滚动 - JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43568870/