我怎样才能使这段代码只平滑滚动我想要的元素

How can I get this code to only smooth scroll only the elements I want?

本文关键字:代码 平滑 滚动 元素 我想要 段代码      更新时间:2023-09-26

我有一个流畅的滚动代码,它工作得很好,问题是它工作得太好了。我还有其他使用"#"作为标签的元素(例如:),但我不希望标签被平滑滚动定位。我有以下平滑滚动代码:

    jQuery(document).ready(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
     }, 1000);
     return false;
   }
 }
});
});

是否可以修改为只针对页面的锚点而不是标签锚点

如果您不想影响以#作为href值的链接,您应该使用的语法如下所示:

$("[attribute!='value']")

在你的例子中,你指定href为属性,#为值。

$("a[href!='#']").on('click', function(e){
    e.preventDefault();
    //do stuff
});