[英]jQuery: Auto scroll to top
我用这个脚本打开一个模态:
<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;
之前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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.