jQuery smooth scroll full url including id

怎甘沉沦 提交于 2019-12-13 06:17:44

问题


Just wondering how to enable smooth scroll using full url.

This is the nav

<nav class="primary-nav">
  <ul>
    <li><a href="http://domainname.com/">Home</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#services">Services</a></li>
    <li><a href="http://domainname.com/contact">Contact</a></li>
  </ul>
</nav>

Would like to use

<nav class="primary-nav">
  <ul>
    <li><a href="http://domainname.com/">Home</a></li>
    <li><a href="http://domainname.com/#about">About</a></li>
    <li><a href="http://domainname.com/#services">Services</a></li>
    <li><a href="http://domainname.com/contact">Contact</a></li>
  </ul>
</nav>

and this is the jQuery code used to scroll to sections on the page.

function smoothScroll(duration) {
 $('a[href^="#"]').on('click', function (event) {
  var target = $($(this).attr('href'));
   if (target.length) {
     event.preventDefault();
     $('html, body').animate({
      scrollTop: target.offset().top
     }, duration);
   }
  });
 }

Any help would be great thanks.


回答1:


As far as I understand you want to stay on the same page, just for some reason you want your internal links to be absolute.

To achieve internal linking with absolute URLs you could change it like that:

JavaScript:

 var duration = 1000;
 var domainname = 'http://domainname.com/';

 $('a[href^="'+domainname+'#"]').on('click', function (event) {
   var target = $(this).attr('href');
   if (target.length) {
     event.preventDefault();

     target = $( target.replace(domainname, '') );

     $('html, body').animate({
        scrollTop: target.offset().top
     }, duration);
   }
  });

Explanation: You change the selector so that it not activates on URLs like '#about' but 'http://domainname.com/#about'. Then you cut off the domain name part and you will have a internal link like '#about' again.

Fiddle: https://jsfiddle.net/u5dL9rt3/



来源:https://stackoverflow.com/questions/39410462/jquery-smooth-scroll-full-url-including-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!