最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: keep a div in page center, even if page is scrolled down - Stack Overflow

programmeradmin4浏览0评论

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. I am trying this code (please see jsfiddle), but does not work. Can someone help me with it? Thanks.

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. I am trying this code (please see jsfiddle), but does not work. Can someone help me with it? Thanks.

Share Improve this question asked Aug 26, 2011 at 19:40 billabilla 2811 gold badge3 silver badges9 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

You don't need jquery for that, just use css

HTML

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

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? Then you don't need any form of javascript trickery.

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

Here you go. Updated with a scroll event and consideration of document.body.scrollTop

http://jsfiddle/8Dupa/4/

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

and within center()

top += document.body.scrollTop;

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();
发布评论

评论列表(0)

  1. 暂无评论