element.offsetWidth 与 element.style.width的区别

来源:互联网 发布:wind数据库使用方法 编辑:程序博客网 时间:2024/06/05 04:54

请先 下载demo事例

下载后,请依次点击div,仔细观看弹出框里面的内容,仔细比较一下,你就能看到区别。

不愿意下载的童鞋也可以自己复制啊!微笑

html:

<!DOCTYPE html><html><head>    <meta charset="UTF-8"><title>Hello, World</title>    <link rel="stylesheet" href="static/css/aio.css" /></head><body>    <div class="div1 box" id="div1" style="width:200px">我是div1<br/>点我看看我的类型</div>      <div class="div2 box" id="div2">我是div2<br/>点我看看我的类型</div>     <hr/>    <div class="div3 box" id="div3" style="width:200px">我是div3<br/>我有padding border width</div>      <div class="div4 box" id="div4">我是div4<br/>我有padding border width </div>     <hr/>    <div class="div5 box" id="div5" style="width:200px">我是div5<br/>你可以改变我的宽度</div>      <div class="div6 box" id="div6">我是div6<br/>但你改变不了我的宽度!嘻嘻</div> <hr/><div class="div7 box" id="div7" style="width:200px">我是div7<br/>我的样式在行间</div>      <div class="div8 box" id="div8">我是div8<br/>我的样式在css里面</div> <script src="static/js/test.js"></script></body></html>
css:

/*!/css/style.scss*/body {  background-color: #FFCCFF;}.box {  margin: 20px;  height: 200px;  display: inline-block;  background-color: blue;  vertical-align: top;}.div2 {  width: 200px;}.div3 {  padding: 5px;  border: 5px solid red;}.div4 {  padding: 5px;  width: 200px;  border: 5px solid red;}.div6 {  width: 200px;}.div8 {  width: 200px;}
js:

window.onload=function() {var odiv1 = document.getElementById('div1');var odiv2 = document.getElementById('div2');var odiv3 = document.getElementById('div3');var odiv4 = document.getElementById('div4');var odiv5 = document.getElementById('div5');var odiv6 = document.getElementById('div6');var odiv7 = document.getElementById('div7');var odiv8 = document.getElementById('div8');odiv1.onclick =function(){var width = odiv1.style.width;alert("div1宽度:"+width+"\n"+"div1类型为:"+typeof(width));console.log("div1宽度:"+width+"\n"+"div1类型为:"+typeof(width));}odiv2.onclick =function(){var width = odiv2.offsetWidth;alert("div2宽度:"+width+"\n"+"div2类型为:"+typeof(width));console.log("div2宽度:"+width+"\n"+"div2类型为:"+typeof(width));}odiv3.onclick =function(){var width = odiv3.style.width;alert("div3宽度:"+width);console.log("div3宽度:"+width);}odiv4.onclick =function(){var width = odiv4.offsetWidth;alert("div4宽度:"+width);console.log("div4宽度:"+width);}odiv5.onclick =function(){odiv5.style.width = 300+'px';}odiv6.onclick =function(){odiv6.offsetWidth = 300;}odiv7.onclick =function(){var width = odiv7.style.width;alert("div4宽度:"+width);console.log("div4宽度:"+width);}odiv8.onclick =function(){var width = odiv8.style.width;alert("div4宽度:"+width);console.log("div4宽度:"+width);}}


两者区别表区别style.widthoffsetWidth类型区别stringnumber宽度区别本身的div的widthpadding+border+width读写属性可读可写只读

最后一点。style.width只能获取到div的行间宽度。要想获取到css里面的宽度的话。就要用到getComputerStyle( element, op ).width 

IE下用element.currentStyle.width。


0 0
原创粉丝点击