JS中获取dom元素属性的方法有两种
方式一:dom.style.xxx
该方法只能获取行内样式的属性值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.div1 {
width: 100px;
height: 100px;
background-color: #000;
}
</style>
</head>
<body>
<div class="div1"></div>
<script>
const div1 = document.querySelector('.div1');
console.log(box.style) //这里我们打开控制台可以看到width: "";
console.log(box.style.width) //这里我们就无法打印出任何东西
</script>
</body>
</html>
方法二:getComputedStyle(dom).xxx
该方法可以打印出所有的dom属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.div1 {
width: 100px;
height: 100px;
background-color: #000;
}
</style>
</head>
<body>
<div class="div1"></div>
<script>
const div1 = document.querySelector('.div1');
console.log(getComputedStyle(div1).width)
</script>
</body>
</html>