页面加载时显示“返回顶部”按钮,滚动前。

7
我按照教程添加了一个"回到顶部"的粘滞按钮,它会在页面向下滚动时出现。但是奇怪的是,在页面首次加载后,当您处于页面顶部时,它就会显示出来。如果您向下滚动,然后再完全向上滚动,它将消失(应该如此)。但最初它的行为不正常。有任何想法吗?
这是我正在使用它的实时页面,您可以在这里看到它位于右下角:http://willryan.us
<a href="#" class="go-top" style="display: inline;">Back to top</a>


<script>
        $(document).ready(function() {
            // Show or hide the sticky footer button
            $(window).scroll(function() {
                if ($(this).scrollTop() > 200) {
                    $('.go-top').fadeIn(500);
                } else {
                    $('.go-top').fadeOut(300);
                }
            });

            // Animate the scroll to top
            $('.go-top').click(function(event) {
                event.preventDefault();

                $('html, body').animate({scrollTop: 0}, 300);
            })
        });
    </script>

CSS

.go-top {
    position: fixed;
    bottom: 0.75em;
    right: 0.5em;
    text-decoration: none;
    color: white;
    background-color: rgba(0, 0, 0, 0.25);
    font-size: 12px;
    padding: 10px;
    display: none;
    margin: 0;
}

.go-top:hover {
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    text-decoration: none;
}

1
你正在加载具有 display:inline 属性的元素,请将其更改为 display:none,这样在首次加载时它就不会出现。 - ntgCleaner
你是在说“.go-top”类吗?它确实有display:none。编辑:啊,你是在说HTML。我现在会尝试一下,谢谢。 - Will Ryan
你的HTML有一个内联样式,其中包含display:inline - 要么使你的样式表说display:none !important;,要么将你的内联样式更改为相同的内容。 - ntgCleaner
@WillRyan 他在谈论的是第一行代码 - <a>。 - Grzegorz
搞定了!谢谢!奇怪...教程明确指出那个HTML块应该使用display:inline。 - Will Ryan
my answer is below ;) - ntgCleaner
3个回答

12

从以下HTML更改:

<a href="#" class="go-top" style="display: inline;">Back to top</a>
<a href="#" class="go-top" style="display: none;">Back to top</a>

这将最初隐藏您的按钮,直到您滚动。


6

显示该内容是因为您尚未触发滚动事件以执行隐藏/显示逻辑。

<script>
    $(document).ready(function() {
        function checkPosition() {
            if ($(this).scrollTop() > 200) {
                $('.go-top').fadeIn(500);
            } else {
                $('.go-top').fadeOut(300);
            }
        }
        // Show or hide the sticky footer button
        $(window).scroll(checkPosition);

        // Animate the scroll to top
        $('.go-top').click(function(event) {
            event.preventDefault();

            $('html, body').animate({scrollTop: 0}, 300);
        })

        checkPosition();
    });
</script>

这个新的重构将在页面加载时至少触发一次checkPosition,以确保按钮已经淡化。另一种解决方案是在CSS中设置display: none;,使元素默认隐藏,然后仅在稍后由JavaScript显示。

我的理解是,这段代码默认情况下会将其隐藏,然后在滚动时显示出来。 - Will Ryan
是的,不过这并不是因为隐藏部分只有在开始滚动时才运行。您需要在页面加载时至少运行一次“位置”检查来隐藏它。请参见我在底部提供的替代解决方案。 - Alex Mcp
这也将使它在加载时“淡出”。因此,您将看到它在加载时淡出。 - ntgCleaner
是的,说得好。CSS/内联display: none选项更好。 - Alex Mcp

1

我按照用户ntgCleaner的建议,将HTML中的"display:inline"改为"display:none",看起来似乎已经生效了。谢谢!


抱歉,直到现在才看到你的另一条评论,之前只看到了你在我的帖子上的原始评论。我刚刚选择了你的答案作为正确答案,再次感谢! - Will Ryan
随时!很高兴能帮助到您。 - ntgCleaner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接