【问题标题】:Animate scroll jquery not working动画滚动jQuery不起作用
【发布时间】:2014-11-06 04:51:51
【问题描述】:

所以我想我可能知道我的问题是什么——为了使我的网站具有响应性,我使用了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

【问题讨论】:

    标签: javascript jquery html scroll


    【解决方案1】:

    试试这个demo

     $(".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>

    【讨论】:

    • hmmm 我之前尝试过&lt;a&gt; 标签,不幸的是它不起作用:/ 如果我没记错的话,偏移值在px?如果是这样,我认为这是我的问题。当滚动目标之前px 中所有元素高度的总和明显更大时,记录到控制台的偏移值约为 700。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多