JQuery 动画 ScrollTop 不起作用

JQuery Animate ScrollTop doesn't work

我试图通过单击绿色块使页面向下滚动到“.block3”。我在这里错过了什么?我似乎无法让它工作,我检查了类似的主题,但没有运气。

$(document).ready(function() {
  $('.down').click(function() {
    alert("y no work?");
    $('html', 'body').animate({
      scrollTop: $('.block3').offset().top
    }, 800, "easeOutQuart");
  });
});
.down {
  background: green;
  width: 50px;
  height: 50px;
}
.block1,.block2,.block3 {
  background: red;
  width: 200px;
  height: 600px;
  margin: 1em 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="down"></div>
<div class="block1"></div>
<div class="block2"></div>
<div class="block3"></div>

问题出在 selector。您一次只能滚动一个元素。为了简化您需要额外的库。

我注意到您的卷轴没有到达终点。我想那是缩进

$(document).ready(function() {

 $('.down').click(function() {
  $('body').animate({scrollTop:$('.block3').offset().top}, 800, 'linear');
 });
 
 });
.down {background:green; width:50px; height:50px; }
.block1, .block2, .block3 { background:red; width:200px; height:600px; margin: 1em 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="down"></div>

<div class="block1"></div>

<div class="block2"></div>

<div class="block3"></div>

试试这个:

您必须用逗号分隔每个选择器。

$(document).ready(function() {
    
    $('.down').click(function() {
        
        alert("y no work?");
        
        $('html,body').animate({
            
            scrollTop: $('.block3').offset().top}, 800, "linear");
    })
    
})
 .down {background:green; width:50px; height:50px; }
.block1, .block2, .block3 { background:red; width:200px; height:600px; margin: 1em 0;}
<div class="down"></div>

<div class="block1"></div>

<div class="block2"></div>

<div class="block3"></div>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

我注意到你没有 JQuery UI,这可能是 easeOutQuart 不起作用的原因,如果你不想使用 [=linear 就可以了=10=].

要包括easeOutQuart或其他特殊的ui,包括JQuery UI

只需包含 jquery UI

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<html>
<body>
<div class="down"></div>

<div class="block1"></div>

<div class="block2"></div>

<div class="block3"></div>
<style>
.down {background:green; width:50px; height:50px; }
.block1, .block2, .block3 { background:red; width:200px; height:600px; margin: 1em 0;}
</style>
<script>
 $(document).ready(function() {

 $('.down').click(function() {
        alert("y no work?");
  $("html, body").animate({scrollTop:$('.block3').position().top}, 800, "easeOutQuart");
 });
 
 });
</script>
</body>
</html>

库然后再试一次你的脚本应该完美的一切。

谢谢!

而不是使用:

$("html, body").animate({scrollTop:$('.block3').position().top}, 800, "easeOutQuart");

使用顶部+对象高度:

$("html, body").animate({scrollTop:$('.block3').position().top + $('.block3').height()}, 800, "easeOutQuart");