标签:pre 技术 getc 通过 content current div ons etc
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>>js获取盒模型宽和高的方法</title>
<style>
*{
margin: 0;
padding: 0;
}
#div1{
width: 100px;
height: 100px;
padding: 10px;
border:10px solid #000000;
background: #ffff00;
}
#div2{
width: 100px;
height: 100px;
padding: 10px;
border:10px solid #0000ff;
background: #ff0000;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>dom.style.width/height;</p>
<div id="div1" style="width: 100px">哟哟哟</div>
<div id="div2">嘿嘿嘿</div>
<script>
var oDiv1 = document.getElementById("div1");
console.log(oDiv1.style.width ) ;
</script>
</body>
</html>
效果图:
缺点:通过这种方式,只能获取行内样式,不能获取内嵌的样式和外链的样式。
⑵这种方法获取的是浏览器渲染以后的元素的宽和高,这种写法兼容性更好一些。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>>js获取盒模型宽和高的方法</title>
<style>
*{
margin: 0;
padding: 0;
}
#div1{
width: 100px;
height: 100px;
padding: 10px;
border:10px solid #000000;
background: #ffff00;
}
#div2{
width: 100px;
height: 100px;
padding: 10px;
border:10px solid #0000ff;
background: #ff0000;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>window.getComputedStyle(element).width/height;</p>
<div id="div1" >111</div>
<div id="div2">222</div>
<script>
var oDiv1 = document.getElementById("div1");
console.log( window.getComputedStyle(oDiv1).width ) ;
</script>
</body>
</html>
效果图:
㈢方式三(IE独有的)
⑴dom.currentStyle.width/height
⑵这种方法获取的是浏览器渲染以后的元素的宽和高,无论是用何种方式引入的css样式都可以,但只有IE浏览器支持这种写法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>>js获取盒模型宽和高的方法</title>
<style>
*{
margin: 0;
padding: 0;
}
#div1{
width: 100px;
height: 100px;
padding: 10px;
border:10px solid #000000;
background: #ffff00;
}
#div2{
width: 100px;
height: 100px;
padding: 10px;
border:10px solid #0000ff;
background: #ff0000;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>dom.currentStyle.width/height;</p>
<div id="div1" >哟哟哟</div>
<div id="div2">呵呵呵</div>
<script>
var oDiv1 = document.getElementById("div1");
console.log( oDiv1.currentStyle.width);
</script>
</body>
</html>
效果图:
⑴dom.getBoundingClientRect().width/height
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>>js获取盒模型宽和高的方法</title>
<style>
*{
margin: 0;
padding: 0;
}
#div1{
width: 100px;
height: 100px;
padding: 10px;
border:10px solid #000000;
background: #ffff00;
}
#div2{
width: 100px;
height: 100px;
padding: 10px;
border:10px solid #0000ff;
background: #ff0000;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>dom.getBoundingClientRect().width/height;</p>
<div id="div1" >111</div>
<div id="div2">222</div>
<script>
var oDiv1 = document.getElementById("div1");
console.log(oDiv1.getBoundingClientRect().width);
</script>
</body>
</html>
效果图:
标签:pre 技术 getc 通过 content current div ons etc
原文地址:https://www.cnblogs.com/shihaiying/p/11600229.html