方法一:DOM节点.offsetWidth/offsetHeight
作用:获取到的是内容区域(content) + 内边距(padding) + 边框(border)
的值,输出一个数字。
<style type="text/css">
div{
width: 100px;
height: 100px;
padding: 10px;
border: 10px solid blue;
margin: 10px;
}
</style>
<body>
<div></div>
</body>
<script>
var dom = document.getElementsByTagName("div")[0];
console.log(dom.offsetWidth); //140
console.log(dom.offsetHeight); //140
</script>
方法二:DOM节点.clientWidth/clientHeight
作用:获取到的是内容区域(content) + 内边距(padding)
的值,输出一个数字。
<style type="text/css">
div{
width: 100px;
height: 100px;
padding: 10px;
border: 10px solid blue;
margin: 10px;
}
</style>
<body>
<div></div>
</body>
<script>
var dom = document.getElementsByTagName("div")[0];
console.log(dom.clientWidth); //120
console.log(dom.clientHeight); //120
</script>
方法三:DOM节点.style.width/height
作用:获取内联样式设置的宽高;
缺点:获取不到嵌入样式和外部样式。
<style type="text/css">
div{
height: 100px;
}
</style>
<body>
<div style="width:100px;"></div>
</body>
<script>
var dom = document.getElementsByTagName("div")[0];
console.log(dom.style.width); //100px
console.log(dom.style.height); //""
</script>
方法四:DOM节点.currentStyle.width/height
作用:获取元素渲染之后的宽高;
缺点:只能在IE浏览器使用。
<style type="text/css">
div{
height: 100px;
width: 100px;
}
</style>
<body>
<div></div>
</body>
<script>
var dom = document.getElementsByTagName("div")[0];
console.log(dom.currentStyle.width); //100px
console.log(dom.currentStyle.height); //100px
</script>
方法五:window.getComputedStyle(DOM节点).width/height
作用:获取元素宽高的最终计算值;
缺点:不兼容IE8及以下版本。
<style type="text/css">
div{
height: 100px;
width: 100px;
}
</style>
<body>
<div></div>
</body>
<script>
var dom = document.getElementsByTagName("div")[0];
console.log(window.getComputedStyle(dom,null).width); //100px
console.log(window.getComputedStyle(dom,null).height); //100px
</script>
方法六:DOM节点.getBoundingClientRect().width/height
作用:获取到的是内容区域(content) + 内边距(padding) + 边框(border)
的值,输出一个数字。
<style type="text/css">
div{
height: 100px;
width: 100px;
padding: 10px;
border: 10px solid blue;
margin: 10px;
}
</style>
<body>
<div></div>
</body>
<script>
var dom = document.getElementsByTagName("div")[0];
console.log(dom.getBoundingClientRect().width); //140
console.log(dom.getBoundingClientRect().height); //140
</script>