动画滚动jquery不工作

Animate scroll jquery not working

本文关键字:工作 jquery 滚动 动画      更新时间:2023-09-26

所以我想我可能已经知道我的问题是什么了——为了让我的网站响应,我使用了height:auto,并使用min-height:some-percentage设置了高度。我知道这可能不是最佳实践,但它很有效,而且比媒体查询花费的时间要少得多。

因此,当我没有使用上述方法设置高度时,下面的动画滚动代码就可以工作了:

$('.animate_scroll').click(function(e){
    e.preventDefault(); //I tried without this line
    var loc_id = $($(this).attr('href')),
        loc_pos = loc_id.offset().top;
    console.log($(this).attr('href')); //outputs the right div id
    console.log(loc_pos); //outputs offset greater than 0
    $('html, body').animate({scrollTop : loc_pos}, 300)
})

有人知道我做错了什么吗?我之所以说我想我已经知道我的问题是什么了,是因为上面的console.log语句记录了有效值。

更新:在上面的代码中,我又添加了几个console.log语句来获取偏移量值。值是不同的,但即使我将loc_id设置为document.getElementById(this.getAttribute('id')).offsetTop,然后将其用作scrollTop值,它也不会滚动。

console.log($(this).attr('href')); //correct id
console.log(loc_pos); //outputs 794.546875
console.log(document.getElementById(this.getAttribute('id')).offsetTop); //944

尝试这个演示

 $(".jumper").on("click", function( e ) {
        e.preventDefault();
        $("body, html").animate({ 
            scrollTop: $( $(this).attr('href') ).offset().top 
        }, 2000);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="pliip">pliip</div><a class="jumper" href="#ploop">Ploop</a><a id="#a_id">LINK TO MOVE</a>
<div style="height:1000px;background-color:#666">div</div>
<!-- Landing elements -->
<a class="jumper" href="#pliip">Pliip</a>
<div id="ploop">ploop</div>