一共有三种方法
方法一:offsetHeight 与 clientHeight
offsetHeight:总高度
clientHeight:总高度 - 边框*2
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#div1 {width: 200px;height: 200px;padding:10px;border:2px solid red;background-color: rgb(41, 126, 165);}</style></head><body><div id='div1'></div><script>var div=document.getElementById('div1');console.log(div.offsetHeight);//224 加边框console.log(div.clientHeight);//220 不加边框</script></body></html>
方法二:style.width
获得的是content的高度,但只有写成内联样式时才有高度输出
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#div1 {width: 200px;height: 200px;padding:10px;border:2px solid red;background-color: rgb(41, 126, 165);}</style></head><body><div id='div1'></div><div id='div2' style="width:200px"></div>//内联样式<script>var div1=document.getElementById('div1');console.log(div1.style.width);//为空var div2=document.getElementById('div2');console.log(div2.style.width);//200px</script></body></html>
方法三:getComputedStyle
能够获得元素所有的css样式(就算没有样式,但也会罗列出来),但是只可以读取,不可以修改。
使用getPropertyValue(‘属性名’)获得对应样式值
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#div1 {width: 200px;height: 200px;padding:10px;border:2px solid red;background-color: rgb(41, 126, 165);}</style></head><body><div id='div1'></div><script>var div1=document.getElementById('div1');console.log(window.getComputedStyle(div1));//显示所有样式console.log(window.getComputedStyle(div1).getPropertyValue('width'));//200px</script></body></html>