[英]Center div vertically and horizontally center even when page scrolled down
[英]jQuery: keep a div in page center, even if page is scrolled down
您不需要jquery,只需使用CSS
的HTML
<div id="senad">content</div>
的CSS
#senad { width: 200px; height: 200px; position: fixed; top: 50%; left: 50%; border: 1px solid gray;}
錫將保持元素居中。
為什么不只是將其標記在position: fixed
無論用戶在哪里滾動,都將其position: fixed
並保持在該位置? 然后,您不需要任何形式的JavaScript欺騙。
但是,要回答您當前的問題,似乎您只提供了一次居中,但是您從未對窗口的滾動事件做出反應:
$(window).scroll(function() { $('#box').center(); });
使用這個插件:
jQuery.fn.center = function(){
this.css("position","absolute");
this.css("top","50%");
this.css("left","50%");
this.css("margin-top","-"+(this.height()/2)+"px");
this.css("margin-left","-"+(this.width()/2)+"px");
return this;}
$("#id").center();
干得好。 更新了滾動事件並考慮了document.body.scrollTop
$(window).scroll(function(){$('#box')。center();});
在center()之內
頂部+ = document.body.scrollTop;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.