简体   繁体   English

Javascript 平滑滚动冲突

[英]Javascript smooth scroll conflict

I am using the pretty standard smooth scrolling javascript to link to anchor points on the same pages in my wordpress site and it works fine.我正在使用非常标准的平滑滚动 javascript 链接到我的 wordpress 站点中相同页面上的锚点,它工作正常。 However, I get no response from a link/button when trying to open an anchor point on another page.但是,在尝试打开另一个页面上的锚点时,我没有从链接/按钮得到响应。 It's like the link/button is completely dead.就像链接/按钮完全死了。 It works fine if I right click on it and select open in a new tab.如果我右键单击它并在新选项卡中打开 select,它工作正常。 It also works if I remove the offending javascript from the site header.如果我从站点 header 中删除有问题的 javascript,它也可以工作。 Can anybody suggest where the conflict may lie?任何人都可以建议冲突可能在哪里吗? For those who may not be familiar, this is the offending code:对于那些可能不熟悉的人,这是有问题的代码:

$(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
  });
});

This code seems to assume that every link to an anchor will be to the anchor on the current page .此代码似乎假定每个指向锚点的链接都指向当前页面上的锚点。 You need to add code to detect if the link is going to a different page, and if so, navigate directly there (rather than attempt the smooth-scroll effect to the anchor on the current page).您需要添加代码来检测链接是否指向不同的页面,如果是,则直接导航到那里(而不是尝试平滑滚动效果到当前页面上的锚点)。

Add this code to the beginning of your click handler:将此代码添加到单击处理程序的开头:

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

You need to animate to the event.target the clicked Dom element, not to string variable hash您需要对事件进行动画处理。 hash单击的 Dom 元素,而不是字符串变量event.target

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM