【问题标题】:scrollTop jQuery, scrolling to div with id?scrollTop jQuery,滚动到带有 id 的 div?
【发布时间】:2011-06-01 17:04:11
【问题描述】:

这是我当前的代码

$(document).ready(function() {
    $('.abouta').click(function(){
        $('html, body').animate({scrollTop:308}, 'slow');
        return false;
    });
    $('.portfolioa').click(function(){
        $('html, body').animate({scrollTop:708}, 'slow');
        return false;
    });
    $('.contacta').click(function(){
        $('html, body').animate({scrollTop:1108}, 'slow');
        return false;
    });
});

当您单击链接时,例如'abouta' 它滚动到页面的特定部分。我宁愿做一个scrollTo,然后是一个div的id,这样如果我改变填充等,我就不必不断改变scrollTo的位置。有什么办法吗?

【问题讨论】:

    标签: javascript jquery css scroll position


    【解决方案1】:

    而不是

    $('html, body').animate({scrollTop:xxx}, 'slow');
    

    使用

    $('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');
    

    这将返回您选择为#div_id的任何元素的绝对顶部位置

    【讨论】:

    • 我很惊讶这么长时间没有人发表评论 - 就目前的问题而言,确实要求 .offset() 而不是 .position() 作为解决方案,对吧?目标 div 可以是页面上的任何位置,.position()returns the top offset relative to its container box。因此,如果目标 div 是其父级的第一个子级,则上述代码会将您带到文档的顶部。还是我错过了什么?
    • 感谢 Sameers,这正是我遇到的问题。 .offset() 是一种享受。
    【解决方案2】:

    如果你只想滚动某个 div,可以使用 div id 代替 'html, body'

    $('html, body').animate(...
    

    使用

    $('#mydivid').animate(...
    

    【讨论】:

    • 不,$('#div').animate({scrollTop:$('#div').position().top}, 'slow'); 不起作用。 (铬 23)。更好地使用$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');
    【解决方案3】:

    试试这个:

    $('html, body').animate({scrollTop:$('#xxx').position().top}, 'slow');
    $('#xxx').focus();
    

    【讨论】:

      【解决方案4】:

      试试这个

          $('#div_id').animate({scrollTop:0}, '500', 'swing');
      

      【讨论】:

        【解决方案5】:

        我的解决方案如下:

        document.getElementById("agent_details").scrollIntoView();
        

        【讨论】:

        • 我需要它来滚动顶部到 html 表的特定行。这适用于行 id 属性。
        【解决方案6】:

        使用这个:

        $('html').animate({ scrollTop: $("#yourDiv").offset().top-100 }, "slow");
        

        【讨论】:

          猜你喜欢
          • 2010-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-14
          • 2023-03-17
          • 2013-10-01
          • 1970-01-01
          • 2016-06-02
          相关资源
          最近更新 更多