javascript - 如何一次不快速地轻柔滚动

标签 javascript html css

我是 html 的初学者,想问一下如何移动到 html 中的 id,该 id 由 anchor 标记定位,例如:

当我运行此代码时,它会快速转到目标 id,尽管我想使用动画。我该怎么做?

最佳答案

您可以使用 jQuery 实现这一点。

这是执行平滑页面滚动到同一页面上的 anchor 的代码。它内置了一些逻辑来识别那些跳转链接,而不是针对其他链接。

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });

关于javascript - 如何一次不快速地轻柔滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44394184/

相关文章:

html - 将固定宽度应用于 body 会导致对齐问题

html - 将标题元素与图像对齐

javascript - 如何使用 setCustomValidity() API 将错误消息添加到时间表单

javascript - 相对于背景当前位置的视差

javascript - 我如何强制 DOM 在 Javascript/jQuery 中重新求值?

css - IE9 总是在我的 DEV 服务器上恢复到 IE7 标准,而不是在 PROD 中

html - 如何通过 attr() 将 HTML `data-` 字符串属性传递到 SCSS mixin?

html - DOMPDF 0.8.1 固定页眉和页脚不显示在第一页上

javascript - 如何在模块命名空间中使用 Vuex 类型常量?

javascript - jQuery,slicknav 插件,长菜单溢出 y