<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #box{100px;height:100px;border: solid 3px black;} </style> </head> <body> <div id="box" style="background: red"></div> </body> <script> var obox = document.getElementById("box") // 可以获取和设置,行内样式 console.log(obox.style.border) //空白 console.log(obox.style.background) //red // // //// 非行内样式的操作,只能获取不能设置 console.log(getComputedStyle(obox,false)) //获取obox的所有css样式 console.log(getComputedStyle(obox,false).width) //100px console.log(getComputedStyle(obox,false).border) //3px solid rgb(0, 0, 0) console.log(getComputedStyle(obox,false).background) //rgb(255, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box //// 不能设置 getComputedStyle(obox,false).background = "yellow"; //报错
//IE浏览器 console.log(obox.currentStyle) console.log(obox.currentStyle.width) console.log(obox.currentStyle.border) console.log(obox.currentStyle.background)
兼容(将其封装成一个函数以便随时调用) function getStyle(ele,attr){ var a = ""; if(ele.currentStyle){ a = ele.currentStyle[attr]; }else{ a = getComputedStyle(ele,false)[attr]; } return a; } console.log(getStyle(obox,"width")) //100px
</script> </html>
获取值尺寸样式:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #box{100px;height:100px;padding: 10px;border: 20px solid black;margin: 30px;position: absolute;left:50px;top:50px} </style> </head> <body> <div id="box">可视区域的宽高可视区域的宽高可视区域的宽高可视区域的宽高可视区域的宽高可视区域的宽高可视区域的宽高可视区域的宽高可视区域的宽高可视区域的宽高可视区域的宽高</div> </body> <script> var obox = document.getElementById("box"); // 可视内容区域的宽高 console.log(obox.clientWidth) //120 content+padding console.log(obox.clientHeight) //120 // 包括滚动区域的宽高 console.log(obox.scrollWidth) //120 console.log(obox.scrollHeight) //283 content+padding+scrool // 可视边框区域的宽高 console.log(obox.offsetWidth) //160 content+border+padding console.log(obox.offsetHeight) //160 // 元素相对于包含块偏移的位置 console.log(obox.offsetLeft) //80 left+margin console.log(obox.offsetTop) //80 // 滚动的left和top console.log(obox.scrollTop) //margin+top console.log(obox.scrollLeft)// // 获取当前元素的包含块 console.log(obox.offsetParent); //<body>.....</body> </script> </html>