向下滚动之前显示在页面加载上的粘滞的“返回顶部”按钮

问题描述 投票:7回答:3

我遵循了教程的操作,获得了一个粘滞的“返回顶部”按钮,该按钮将在您向下滚动时显示。由于某种原因,页面首次加载后显示在页面顶部时,会显示该页面。如果向下滚动,然后一直返回,它就会消失(应有的样子)。但是最初它的行为不正常。有什么主意吗?

这是我正在使用的实时页面,您可以在右下角看到它:http://willryan.us

HTML

<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;
}
javascript jquery css scroll jquery-animate
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之后显示


1
投票

我按照ntgCleaner用户所说的那样,将html中的“ display:inline”更改为“ display:none”,它似乎可以正常工作。谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.