jQuery:自动滚动到顶部

jQuery: Auto scroll to top

本文关键字:顶部 滚动 jQuery      更新时间:2023-09-26

我使用此脚本打开一个模态:

    <script type="text/javascript">
$(function(){
$('.compose').click(function() { 
    $('#popup_bestanden_edit_name').reveal({ 
        animation: 'fade',  
        animationspeed: 600,  
        closeonbackgroundclick: true,  
        dismissModalClass: 'close',
            });
    return false;
});
}); </script>

但是当我在页面底部并单击链接时,模态会在页面顶部打开。所以看起来什么也没发生,但我必须滚动到顶部才能看到打开的模态。

是否可以在

打开模态时自动将用户发送到顶部?

使用以下代码移动到页面顶部:

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

你可以用其他值代替 0,比如 500(以毫秒为单位),让它慢慢移动到顶部

您可以添加position: fixed,例如top: 30px样式#popup_bestanden_edit_name。如果这样做,无论用户在页面上的哪个位置,模态都将始终出现在同一个位置。但是你必须小心,因为如果模态高于视口,您将无法看到模态的其余部分。

如果你仍然想滚动到顶部(没有动画),使用 JavaScript 你可以把

$('body').scrollTop(0);

就在你return false;之前

顺便说一句,如果您想防止链接的默认操作触发,最好这样做:

$('.compose').click(function(event) {
    // your code here
    event.preventDefault();
}

我建议不要滚动到页面顶部。这不是好的用户体验设计!我们可以在身体上隐藏溢出。因此,一旦弹出窗口进入屏幕,用户将无法滚动。我们需要将位置固定在弹出窗口的主要元素上。

我建议检查下面的片段。

<html>
    <head>
        <title>Example</title>
        <style type="text/css">
            .nooverflow {overflow: hidden;}
            .popup {position: fixed; z-index: 99;}
            .cover {position: fixed; background: #000; opacity: .5; filter: alpha(opacity=50); top: 0; left: 0; width: 100%; height: 100%; z-index: 1000; }
            .popup-conteiner {overflow-y: auto; position: fixed; height: 100%; width: 100%; left: 0; top: 0; z-index: 101;}
            .popup-block {position: relative; top: 100px; z-index: 101;}
        </style>
    </head>
    <body>
        <div id="popup">
            <div class="cover"></div>
            <div class="popup-conteiner">
                <div class="popup-block">
                    <!-- POPUP's HTML GOES HERE -->
                </div>
            </div>
        </div>
    </body>
</html>

但是,如果它不起作用,那么您可以将页面滚动到页面顶部。您也可以使用Rajesh提供的解决方案。我想添加一个条件,如果页面已经动画化,则在执行新动画之前停止。

var htmlBody = $("html,body"),
    top = 0;
if (htmlBody.is(':animated')) {
    htmlBody.stop(true, true);  //Need to stop if it is already being animated
}
htmlBody.animate({ scrollTop: top }, 1000); //Scroll to the top of the page by animating for 1 sec.