简体   繁体   English

jQuery外部页面平滑滚动

[英]Jquery External Page Smooth Scroll

Okay here is the problem i am currently facing how can i get jquery to smooth scroll to an anchor link when the anchor link has a name or a id. 好的,这是我当前面临的问题,当锚链接具有名称或ID时,如何使jquery平滑滚动到锚链接。

<a name="scrollhere"> Smooth Scroll here on page load </a>
<a id="scrollhere"> Smooth Scroll here on page load </a>

so regardless of what the anchor link says it should smooth scroll once the page is loaded. 因此,无论锚定链接说了什么,页面加载后都应该平滑滚动。 Here is the code a guy gave me it works. 这是一个人给我的代码,可以正常工作。 But the only problem is this code only works if this is the secnario 但是唯一的问题是,只有在此条件下,此代码才有效

<a class="scrollhere"> Smooth Scroll here on page load </a>

the code only works if the anchor link has a class of where i want the smooth scroll to go. 该代码仅在锚链接具有我希望平滑滚动到达的位置的类时才有效。 But i want it to be a name and or a id. 但我希望它是一个名称或ID。

$(window).bind("load", function() {
       var urlHash = window.location.href.split("#")[1];
       $('html,body').animate({scrollTop:$('.'+urlHash).offset().top}, 4000);  
});

tell me how i can alter this code to do what i want it to do 告诉我如何更改此代码以执行我想要的操作

You can search for each of the areas you'd like to match on and return the first match, like this: 您可以搜索要匹配的每个区域,然后返回第一个匹配项,如下所示:

$(window).bind("load", function() {
   var urlHash = window.location.href.split("#")[1];
   $('html,body').animate({scrollTop:$('.'+urlHash+', #'+urlHash+', [name='+urlHash+']').first().offset().top}, 4000);
});

To look for an id : 要查找id

scrollTop:$('#'+urlHash);

To look for a name: 要查找名称:

scrollTop:$('[name='+urlHash+']');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM