那些宽高

本文详细解析了网页元素产生偏移的原因及其属性,包括标准流、浮动、边距和定位等,同时介绍了如何通过JavaScript获取元素的偏移位置,并提供了解决IE7下计算样式不规范的方法。

所有元素产生偏移一的参照物是文档(浏览器的左上角)

会产生偏移量的属性:标准流(就是盒子上下排列),float,margin,position的absolute或rellative

定位是在margin外面开始定位的

offsetLeft/offsetTop          左偏移和上偏移

offsetHeight/offsetWidth   内容的宽/高+padding+border

clientWidth/clientHeight     可见内容的宽/高+padding

scrollTop/scrollleft            上卷去的内容/左卷曲的内容

scrollWidth/scrollHeight      内容的实际宽/高

 

jq里的:

$(oDiv).width();//内容的宽

$(oDiv).innerWidth();//clientWidth

$(oDiv).outerWidth();//不加双边距的offsetWidth;

$(oDiv).outerWidth(true);//双边距+offsetWidth;

 

offsetLeft=绝对定位的值+margin(记得margin的值初始化)

经常会把需要把offsetLeft转化为绝对定位。记得margin的值初始化

 

 

/*********把offsetLeft转化为绝对定位**********/

oDiv.style.left=oDiv.offsetLeft+"px";

oDiv.style.margin=0;

oDiv.style.position="absolue"

 

 

offsetParent就是产生偏移的参照物,在默认的文档流下,所有的元素的offsetParent是文档(document页面){body代理},

当这个元素的祖先元素写了绝对定位,则以这个祖先元素为offsetParent

/*************得到偏移量的方法****************/

function getPositon(ele){
var l=ele.offsetLft;
var t=ele.offseTop
while(offSetParent){
var ele=ele.offsetParent;
if(window.navigator.userAgent.indexOf('MSIE 8')>-1){
l+=offSetParent.offsetLeft;
t+=offSetParent.offsetTop;
}else{
l+=ele.offsetLeft+ele.clientLeft;
t+=ele.offsetTop+ele.clientTop;
}
}
return {left:l,top:t
}

 

ie7下currentStyle不规范,是因为他们采取的是浏览器给的默认值,解决方法:把这些标签需要计算的默认值初始化

/*************获得样式第一种************/
function getCss(ele,attr){
if(typeof getComputedStyle=="function"){
return getComputedStyle(ele,null)[attr]
}else{
return ele.currentStyle[attr];
}
}


/*************第二种方法*****************/
function getCss(ele,attr){
try{
return getComputedStyle(ele,null)[attr]
} catch(e){
return ele.currentStyle[attr];
}
}

////////////////////第三种获得样式/////////////////////
function getCss(ele,attr){
if(window getComputedStyle){//window,因为这个变量在ie6/7/8里没有,一个变量如果未定义,不能直接操作(读),但是,一个变量没有声明,可以用typeof去判断,如果是属性没有读限制
return getComputedStyle(ele,null)[attr]
}else{
return ele.currentStyle[attr];
}
}

转载于:https://www.cnblogs.com/into/p/4207111.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值