【问题标题】:Javascript smooth scroll conflictJavascript平滑滚动冲突
【发布时间】:2020-05-10 02:32:14
【问题描述】:

我正在使用非常标准的平滑滚动 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


    【解决方案1】:

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

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

    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;
    }
    

    【讨论】:

      【解决方案2】:

      你需要动画到event.target被点击的Dom元素,而不是字符串变量hash

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多