我需要更进一步this question。
我使用以下代码垂直居中:
var boxheight = $('#notifications').height();
var windowheight = $(window).height();
var boxheight = $('#notifications').height();
var pagecenterH = ((windowheight-boxheight)/2);
$('#notifications').animate({'top': pagecenterH});
如果页面只与窗口一样高,那么效果很好,但如果页面长得多,并且当用户点击打开上面的#notifications
代码时用户位于页面的中间位置,则div会显示为居中从屏幕顶部开始,他们可能会完全错过这个盒子。
如何让代码识别用户在页面上的哪个位置,以便div无论向下滚动多远都会垂直居中显示?
提前致谢!
答案 0 :(得分:1)
您将要使用document
而不是window
。见这里:
在您的代码中,将$(window).height()
替换为$(document).height()
。
如果您希望<div>
始终位于屏幕中心,无论用户在加载<div>
后滚动到何处,您都应使用{{1}并将$(window).height()
的位置设置为固定。你可以在这里看到这个:
答案 1 :(得分:0)
您可以使用position:fixed
相对于窗口而不是相对于页面放置元素。这样它就会显示居中,即使用户滚动也会保持居中。
答案 2 :(得分:0)
尝试下面的代码,在这里我们首先将div放在窗口的中心,以便在用户视图中将它添加到滚动顶部并向左滚动到它 -
$('#notifications').css("position","absolute");
$('#notifications').css("top", ( $(window).height() - $('#notifications').height() ) / 2+$(window).scrollTop() + "px");
$('#notifications').css("left", ( $(window).width() - $('#notifications').width() ) / 2+$(window).scrollLeft() + "px");