`
achun
  • 浏览: 306615 次
  • 性别: Icon_minigender_1
  • 来自: 河南郑州
社区版块
存档分类
最新评论

jQuery 插件 center

阅读更多

本来jQuery有一个certer插件,不过少了一个功能,就是基于视口(ViewPort)的居中.

改写一下,代码如下:

jQuery.fn.center = function(f) {
	return this.each(function(){
		var p = f===false?document.body:this.parentNode;
		if ( p.nodeName.toLowerCase()!= "body" && jQuery.css(p,"position") == 'static' )
			p.style.position = 'relative';
		var s = this.style;
		s.position = 'absolute';
		if(p.nodeName.toLowerCase() == "body")
			var w=$(window);
		if(!f || f == "horizontal") {
			s.left = "0px";
			if(p.nodeName.toLowerCase() == "body") {
				var clientLeft = w.scrollLeft() - 10 + (w.width() - parseInt(jQuery.css(this,"width")))/2;
				s.left = Math.max(clientLeft,0) + "px";
			}else if(((parseInt(jQuery.css(p,"width")) - parseInt(jQuery.css(this,"width")))/2) > 0)
				s.left = ((parseInt(jQuery.css(p,"width")) - parseInt(jQuery.css(this,"width")))/2) + "px";
		}
		if(!f || f == "vertical") {
			s.top = "0px";
			if(p.nodeName.toLowerCase() == "body") {
				var clientHeight = w.scrollTop() - 10 + (w.height() - parseInt(jQuery.css(this,"height")))/2;
				s.top = Math.max(clientHeight,0) + "px";
			}else if(((parseInt(jQuery.css(p,"height")) - parseInt(jQuery.css(this,"height")))/2) > 0)
				s.top = ((parseInt(jQuery.css(p,"height")) - parseInt(jQuery.css(this,"height")))/2) + "px";
		}
	});
};

使用,

$(expr).center();
$(expr).center(false);

如果expr 的 parentNode 是body 或者参数是 false的话就会真的 ViewPort 居中.

另外加的偏移量 10 是个偷懒的方法,比如有了滚动条,会好一些,没有的话视觉上也差别不大,不过没有这个偏移量又有 滚动条的话 视觉上就不太舒服了

分享到:
评论
2 楼 achun 2008-11-26  
longleg 写道

好像加上
Html代码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

就不会出现你说的那10像素的问题。

我的应用里永远都是
xhtml1-strict.dtd
还有就是浏览器之间可能有不同,不过这10像素不是什么重点。
1 楼 longleg 2008-11-26  
好像加上
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

就不会出现你说的那10像素的问题。

相关推荐

Global site tag (gtag.js) - Google Analytics