jQuery:如何在页面加载时滚动到某个锚点/ div?

Pop*_*oko 23 javascript jquery

最近我试图更频繁地使用jquery现在我有一些问题,我想用jquery解决希望你能帮助我.

我有一些网页,其中包含一些锚标记(假设锚点位于页面中间),并且在事件onload上我希望页面从该特定锚标记位置开始,这意味着页面将自动"滚动"到某个地方.

这是我以前的解决方案(因为它将#i添加到我的网址,这非常难看)

window.onload = window.location.hash = 'i';
Run Code Online (Sandbox Code Playgroud)

无论如何,你能告诉我怎样才能用jquery做到这一点?

注意:我不希望用户在到达此位置时感觉到任何幻灯片或效果

Man*_*eUK 32

使用以下简单示例

function scrollToElement(ele) {
    $(window).scrollTop(ele.offset().top).scrollLeft(ele.offset().left);
}
Run Code Online (Sandbox Code Playgroud)

ele你的元素(jQuery)在哪里..例如:scrollToElement($('#myid'));


gra*_*ick 24

没有必要使用jQuery,因为这是本机JavaScript功能

element.scrollIntoView()
Run Code Online (Sandbox Code Playgroud)


Lig*_*oul 13

我已经尝试了几个小时,最简单的方法是阻止浏览器跳转到锚点而不是滚动到它:使用另一个锚点(你不在网站上使用的id).因此,您无需链接到"http://#YourActualID",而是链接到"http:// #NoIDonYourSite".噗,浏览器不会再跳了.

然后检查锚是否已设置(使用下面提供的脚本,从另一个线程中拉出!).并设置您要滚动到的实际ID.

$(document).ready(function(){


  $(window).load(function(){
    // Remove the # from the hash, as different browsers may or may not include it
    var hash = location.hash.replace('#','');

    if(hash != ''){

       // Clear the hash in the URL
       // location.hash = '';   // delete front "//" if you want to change the address bar
        $('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);

       }
   });
});
Run Code Online (Sandbox Code Playgroud)

有关工作示例,请参阅http://pro.lightningsoul.com/?c=media&sc=article&cat=coding&id=30#content.

  • 为什么会有`$(document).ready(function()`和`$(window).load(function()`)? (2认同)