简体   繁体   English

jQuery:即使页面向下滚动,也可以在页面中心保留一个div

[英]jQuery: keep a div in page center, even if page is scrolled down

I want to center a div on the screen so that when the page is scrolled down/up, the div scrolls smoothly to the center of the page. 我想在屏幕上居中放置div,以便在向下/向上滚动页面时,div平滑滚动到页面中心。 I am trying this code (please see jsfiddle), but does not work. 我正在尝试此代码(请参阅jsfiddle),但不起作用。 Can someone help me with it? 有人可以帮我吗? Thanks. 谢谢。

You don't need jquery for that, just use css 您不需要jquery,只需使用CSS

HTML 的HTML

<div id="senad">content</div>

CSS 的CSS

 #senad { width: 200px; height: 200px; position: fixed; top: 50%; left: 50%; border: 1px solid gray;}

Thi will keep element on center. 锡将保持元素居中。

Why not just mark it position: fixed and keep it there regardless of where the user scrolls? 为什么不只是将其标记在position: fixed无论用户在哪里滚动,都将其position: fixed并保持在该位置? Then you don't need any form of javascript trickery. 然后,您不需要任何形式的JavaScript欺骗。

However, to answer your current problem, it seems you provide the centering once, you you never react to the scroll event of the window: 但是,要回答您当前的问题,似乎您只提供了一次居中,但是您从未对窗口的滚动事件做出反应:

 $(window).scroll(function() { $('#box').center(); });

use this plugin: 使用这个插件:

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();

Here you go. 干得好。 Updated with a scroll event and consideration of document.body.scrollTop 更新了滚动事件并考虑了document.body.scrollTop

http://jsfiddle.net/8Dupa/4/ http://jsfiddle.net/8Dupa/4/

$(window).scroll(function() { $('#box').center(); }); $(window).scroll(function(){$('#box')。center();});

and within center() 在center()之内

top += document.body.scrollTop; 顶部+ = document.body.scrollTop;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM