2016-11-13 87 views
0

我正在使用一些jQuery我碰到平滑滚动锚页链接。我现在意识到这个脚本中有一些东西阻止锚链接(例如,'#top')出现在URL中,我确实希望URL中的锚链接。有人能告诉我这是什么部分关闭了默认行为,我能做些什么来重新打开它?脚本阻止锚链接出现在网址中

<script> 
$(function() { 
    $('a[href*="#"]:not([href="#"])').click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
     if (target.length) { 
     $('html, body').animate({ 
      scrollTop: target.offset().top 
     }, 500); 
     return false; 
     } 
    } 
    }); 
}); 
</script> 

回答

0

我还没有一个真正的页面上测试了这一点,设置URL哈希,但在动画的最后,你可以设置散列。

$(function() { 
 
    $('a[href*="#"]:not([href="#"])').click(function() { 
 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
 
     var hash = this.hash, 
 
      target = $(hash); 
 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
 
     if (target.length) { 
 
     $('html, body').animate({ 
 
      scrollTop: target.offset().top 
 
     }, 500, function(){ 
 
      window.location.hash = hash; 
 
     }); 
 
     return false; 
 
     } 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<a href="#foo">bottom</a><br/> 
 
A<br/>B<br/>C<br/>D<br/> 
 
E<br/>F<br/>G<br/>H<br/> 
 
I<br/>J<br/>K<br/>L<br/> 
 
M<br/>N<br/>O<br/>P<br/> 
 
Q<br/>R<br/>S<br/>T<br/> 
 
U<br/>V<br/>W<br/>X<br/> 
 
Y<br/>Z<br/> 
 
<p id="foo">HEY</p>

0

您可以手动在动画完成回调使用window.location.hash

$('a[href*="#"]:not([href="#"])').click(function() { 

    var hash = this.hash; 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
     var target = $(hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
     if (target.length) { 
     $('html, body').animate({ 
      scrollTop: target.offset().top 
     }, 500, 'swing', function(){ 
      window.location.hash = hash; 
     }); 
     return false; 
     } 
    } 
    }); 
+0

你不能比....页面会跳转击败什么插件做。 – epascarello

+0

@epascarello yup ...当然会 – charlietfl