【问题标题】:Firefox ignores smooth scrolling when clicking a scroll-to-top button a second and successive timesFirefox 在第二次和连续单击滚动到顶部按钮时忽略平滑滚动
【发布时间】:2020-04-22 12:09:43
【问题描述】:

我在 Firefox 75 中遇到了一个奇怪的行为,代码如下:

HTML:

<html>
<body>

<div>
Lorem ipsum dolor sit amet consectetur adipiscing elit sociis vivamus euismod, netus arcu pulvinar egestas cras commodo fames dui nostra tortor quam, class duis sagittis fusce pellentesque conubia ornare venenatis hac. Quis pretium nulla ad nisi aliquam euismod nunc, consequat fermentum sociis eros felis tempus, tortor a risus dignissim fusce facilisis. Fermentum erat eget libero tellus semper gravida enim rhoncus, placerat natoque mauris sollicitudin class eros tincidunt augue volutpat, penatibus vel interdum nunc cubilia taciti dictumst.
...
(the rest is omitted for brevity)
</div>

<a rel="nofollow" href="#" class="scroll-to-top-link">
    Go to top link
</a>

<button class="scroll-to-top-button">
    Go to top button
</button>

</body>
</html>

JS:

( function() {
    'use strict';

    // Feature Test
    if ( 'querySelector' in document && 'addEventListener' in window ) {

        var goTopBtnLink = document.querySelector( '.scroll-to-top-link' );
        var goTopBtnButton = document.querySelector( '.scroll-to-top-button' );

        var nativeSmoothScroll = function () {
            window.scroll({
                top: 0,
                left: 0,
                behavior: 'smooth'
            });
        };

        goTopBtnLink.addEventListener( 'click', function( e ) {
            e.preventDefault();
            nativeSmoothScroll();
        });

        goTopBtnButton.addEventListener( 'click', function( e ) {
            nativeSmoothScroll();
        });

    }

} )();

页面有一个滚动到顶部的链接,底部有一个滚动到顶部的按钮。如果我单击链接,页面会平滑滚动到顶部。当我也单击按钮时,但只是第一次。在随后的时间里,页面滚动得太快,忽略了behavior: 'smooth' 选项。

我已经把整个代码放在了小提琴上:

https://jsfiddle.net/mf4rz8hj/9/

Chrome 未显示此行为。 有什么想法吗?

【问题讨论】:

    标签: javascript css scroll dom-events smooth-scrolling


    【解决方案1】:

    为什么不用 CSS 来做呢?

    html {
        scroll-behavior: smooth;
    }
    

    这在 IE 和 Safari 上不起作用。

    【讨论】:

      【解决方案2】:

      如果我删除 button 元素的一些样式,问题就会消失。

      button {
          -webkit-appearance: button;
          background-color: transparent;
          border-style: solid; /* remove this */
          border-width: 1px;
          border-radius: 2px;
          color: inherit;
          cursor: pointer;
          padding: 0.4278em 1.25em; /* or remove this */
          -webkit-transition: color 0.25s ease, background-color 0.25s ease;
          transition: color 0.25s ease, background-color 0.25s ease;
      }
      

      这可能是一个错误,因为某些不相关的 CSS 属性的存在会以这种方式影响 JS 代码是没有意义的。

      【讨论】:

        猜你喜欢
        • 2014-05-14
        • 1970-01-01
        • 2018-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多