单击<a>时如何在Safari上平滑滚动?

时间:2020-05-12 18:18:02

标签: javascript html css

我的导航栏中有这个

    const touchstart = document.querySelector("touch");
  touchstart.addEventListener("touchstart", () => {
    document.querySelector(".demo-input").blur();
  });

我想使页面缓慢向下滚动到href。现在,它在Safari上突然滚动。对于谷歌浏览器,我有这个并且可以正常工作:

<li class="nav-item">
  <a class="nav-link" href="/#frase">¿Como funciona?</a>
</li>

我尝试使用另一个堆栈溢出问题中的Javascript为safari实现平滑滚动,但没有一个起作用。 预先感谢。

3 个答案:

答案 0 :(得分:1)

Safari不支持scroll-behavior: smooth;

要实现内部锚链接的平滑滚动,请添加以下原始JavaScript片(无需jQuery!):

(function() {
    scrollTo();
})();

function scrollTo() {
    const links = document.querySelectorAll('.scroll');
    links.forEach(each => (each.onclick = scrollAnchors));
}

function scrollAnchors(e, respond = null) {
    const distanceToTop = el => Math.floor(el.getBoundingClientRect().top);
    e.preventDefault();
    var targetID = (respond) ? respond.getAttribute('href') : this.getAttribute('href');
    const targetAnchor = document.querySelector(targetID);
    if (!targetAnchor) return;
    const originalTop = distanceToTop(targetAnchor);
    window.scrollBy({ top: originalTop, left: 0, behavior: 'smooth' });
    const checkIfDone = setInterval(function() {
        const atBottom = window.innerHeight + window.pageYOffset >= document.body.offsetHeight - 2;
        if (distanceToTop(targetAnchor) === 0 || atBottom) {
            targetAnchor.tabIndex = '-1';
            targetAnchor.focus();
            window.history.pushState('', '', targetID);
            clearInterval(checkIfDone);
        }
    }, 100);
}

在包含该code snippet之后,任何带有class of scroll的锚链接都将滚动到目标。无需修改,只需将其放入即可。

由于您将nav-link类用于<a> tag,因此可以将scrollTo()函数第一行中的scroll替换为锚点类名称nav-link

Official source of answer 还检查您的href是否工作正常?

答案 1 :(得分:0)

您可以使用此脚本启用向后兼容的平滑滚动。

https://github.com/cferdinandi/smooth-scroll

此外,将您的href更改为href="#frase",不需要/。

答案 2 :(得分:0)

这里有两个我想一起使用的功能。如果在加载时以及单击后以哈希开头的页面内链接中的URL中存在哈希,则将平滑滚动到哈希。您需要为此安装jQuery js库,但最好使用香草javascript

// scroll to hash on click
$("a[href*='#']").on('click',function(e){

  e.preventDefault();
  var $self = $(this);

  if ( $( '#'+$self.attr('href').split('#').pop() ).length ) {
      window.setTimeout(function(){
        $('html, body').animate({

          scrollTop: $( '#'+$self.attr('href').split('#').pop() ).offset().top -140

        }, 2000);
      }, 250);
  } else {
      window.location = window.location.origin + $(this).attr('href');
  }

});

// scroll to hash if in url
$(document).ready(function(){

  if( window.location.hash && $( window.location.hash ) ){

    window.setTimeout(function(){
      $('html, body').animate({
        scrollTop: $( window.location.hash ).offset().top -140
      }, 2000);
    }, 250);
  }

});