Javascript平滑滚动冲突

标签 javascript wordpress smooth-scrolling

我正在使用相当标准的平滑滚动 javascript 链接到我的 WordPress 网站中同一页面上的 anchor ,它工作得很好。但是,当我尝试打开另一个页面上的 anchor 时,我没有收到链接/按钮的响应。就像链接/按钮完全失效了一样。如果我右键单击它并选择在新选项卡中打开,它就可以正常工作。如果我从站点标题中删除有问题的 javascript,它也会起作用。有人能指出冲突可能出在哪里吗?对于那些可能不熟悉的人来说,这是有问题的代码:

$(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

最佳答案

这段代码似乎假设每个指向 anchor 的链接都将指向当前页面上的 anchor 。您需要添加代码来检测链接是否会转到不同的页面,如果是,则直接导航到那里(而不是尝试对当前页面上的 anchor 进行平滑滚动效果)。

将此代码添加到点击处理程序的开头:

if ( document.URL.replace(/#.*$/, "") != $(this).attr('href').replace(/#.*$/, "") ) {
    // Link goes to a different URL than the current page (not counting the hash)
    document.location.href = $(this).attr('href');
    return;
}

关于Javascript平滑滚动冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61706446/

相关文章:

php - woocommerce:删除 get_categories 和 get_tags 上的链接

wordpress - 在单个页面上显示 WordPress 博客的所有评论?

javascript - DevEd 教程中的滚动功能不起作用

jquery - 使用自定义设计的滚动条平滑滚动完整的网站

Javascript解析DOM关系字符串

php - 如何最好地将 mysql 数据实现到一行 javascript 代码中?

javascript - 是否可以使用 prop-types 对常规对象、函数参数和返回值进行类型检查?

javascript - 使用 Internet Explorer 进行调试

php - Wordpress 中的 Animate.css

jQuery 平滑水平滚动