JavaScript平滑滚动冲突

问题描述 投票:1回答:2

我正在使用非常标准的平滑滚动javascript链接到我的wordpress网站中相同页面上的锚点,并且工作正常。但是,当尝试在另一页上打开锚点时,链接/按钮没有响应。就像链接/按钮完全失效。如果我右键单击它,然后在新选项卡中选择“打开”,它将很好地工作。如果我从网站标题中删除有问题的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
  });
});
javascript wordpress smooth-scrolling
2个回答
1
投票

此代码似乎假定到锚点的每个链接都将链接到锚点[[在当前页面上。您需要添加代码以检测链接是否转到另一个页面,如果是,则直接在该页面导航(而不是尝试平滑滚动效果到当前页面的锚点)。

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

if ( document.URL.replace(/#.*$/, "") != $(this).attr('href').replace(/#.*$/, "") ) { // Different URL (not counting the hash) document.location.href = $(this).attr('href'); return; }


0
投票
您需要为单击的Dom元素设置为event.target的动画,而不是为字符串变量hash设置动画>

var hash = event.target.href; $('html, body').animate({ scrollTop: $(event.target).offset().top }, 800, function(){

© www.soinside.com 2019 - 2024. All rights reserved.