导航

使任一dom元素居中的javascript代码

Posted on 2011-10-30 15:52  Little的牛儿  阅读(445)  评论(0)    收藏  举报
javascript代码:
/*
辅助操作dom
@lizaoxu 2011.10.30
*/



if (typeof jscript == 'undefined') {
jscript = function() { }
}


jscript.dom = function() { }


/*
将任意一个dom元素水平居中
innerwidth:只读属性,声明了窗口的文档显示区的高度和宽度,以像素计。
这里的宽度和高度不包括菜单栏、工具栏以及滚动条等的高度。
IE 不支持这些属性。它用 document.documentElement 或
ducument.body (与 IE 的版本相关)的 clientWidth 和 clientHeight 属性作为替代。
offsetWidth:返回元素的高度和宽度,以像素为单位。这是非标准的但却得到很好支持的属性。
round : 把一个数字舍入为最接近的整数
pageXOffset : 设置或返回当前页面相对于窗口显示区左上角的 X 位置。
*/

jscript.dom.layerCenterH = function(inObj){
var ca;
var cb;
var cx;
var iebody;
var deocleft;
if(window.innerWidth){
ca = window.innerWidth;
}else {
ca = document.body.clientWidth;
}
cb = inObj.offsetWidth;
cx = (Math.round(ca / 2)) - (Math.round(cb / 2));
iebody = (document.compatMode && document.compatMode != "BackCompat")?
document.documentElement : document.body; /*依据ie的模式而定*/
dsocleft = document.all ? iebody.scrollLeft : window.pageXOffset ; /*document.all在dom中存在,表示用的是ie,否则不是ie*/

inObj.style.left = cx +dsocleft + "px";
console.log(": "+inObj.style.left);

}//end

/*
垂直居中
*/

jscript.dom.layerCenterV = function(inObj){
var ca;
var cb;
var cy;
var iebody;
var dsoctop;

if(window.innerWidth){
ca = window.innerHeight;
}else {
ca = document.body.clientHeight;
}
cb = inObj.offsetWidth;
cy = (Math.round(ca / 2)) - (Math.round(cb / 2));
iebody = (document.compatMode && document.compatMode != "BackCompat")?
document.documentElement : document.body; /*依据ie的模式而定*/
dsoctop = document.all ? iebody.scrollLeft : window.pageYOffset ; /*document.all在dom中存在,表示用的是ie,否则不是ie*/

inObj.style.top = cy +dsoctop + "px";
console.log(": "+inObj.style.top);
}//end