在 JQuery 的 animate 功能的 top 属性下面的代码中,无法正常工作,但 opacity 属性可以正常工作,您如何看待这个问题?
$(function() {
$(window).on('scroll', function() {
var top = $(this).scrollTop();
$('#lan').animate({
top: top + 'px'
}, 1000);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Test</title>
</head>
<body>
<div id="lan">My First Dangerous</div>
</body>
</html>
答案 0 :(得分:2)
何时?此处的目的是证明“动画”功能有效。
因为您需要将“元素”的“位置”值设置为“绝对,相对或固定”。例如。 position: fixed;
$(function() {
$(window).on('scroll', function() {
var top = $(this).scrollTop();
$('#lan').animate({
top: top + 'px'
}, 100);
});
});
body {
min-height: 2000px
}
#lan {
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lan">My First Dangerous</div>
答案 1 :(得分:0)
$(function() {
$(window).on('scroll', function() {
var top = $(this).scrollTop();
$('#lan').animate({
top: top + 'px'
}, 1000);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Test</title>
<style>
body{
height: 800px;;
overflow:scroll;
}
#lan{
position:relative;
}
</style>
</head>
<body>
<div id="lan">My First Dangerous</div>
</body>
</html>
答案 2 :(得分:0)
我假设您希望有一个元素将其保留在视口中...但是通过动画显示,该元素试图保持滚动。
这是一个有趣的效果。
必须将元素放置在absolute
的后面才能放在scrollTop
的位置。在位置fixed
下,该位置与文档无关,而与视口无关。
现在,滚动播放动画非常危险... scroll
事件像机关枪一样触发。您只是不能在每个滚动事件上触发动画(具有其自身的延迟)。您只会在动画队列中堆积大量相同的动画……而这显然不是这里所期望的。
因此...通过使用标志来知道先前的滚动事件是否已经触发了动画,您可以return
避免触发其他事件。
然后,我建议增加一个延迟,以等待用户滚动结束。那不是绝对的“安全”,但是我想出了400ms的延迟,这是相当不错的。那是因为我也将动画延迟降低到了100ms(快!)。过长的动画延迟可能会导致问题,因为用户可以在动画时间的同时再次滚动...并且结束位置将是错误的。
这不是一个“完美”的解决方案...但这可能已经足够了。
$(function() {
// Variable to be used as a "flag"
scrolling = false;
// Variable to store the scrollTop position
var top;
// scroll handler
$(window).on('scroll', function() {
// Update the top position on every scroll event
top = $(this).scrollTop() + 10;
// Prevent the rest of execution
// before the animation already triggered animation has finished
if (scrolling) {
return;
}
// User is scrolling
scrolling = true;
// Wait a little more before starting the animation
// 400 ms seems like a good delay.
setTimeout(function() {
// Animate!
$('#lan').animate({
top: top + 'px'
}, 100, function() { // Animate quite fast is suggested here
scrolling = false;
});
}, 400); // setTimeout delay (can be longer...)
});
});
body {
min-height: 2000px
}
#lan {
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lan">My First Dangerous</div>
答案 3 :(得分:-1)
您应在<script></script>
末尾放置平衡台</body>
。不在head
部分中。我希望可以
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<div id="lan">My First Dangerous</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>