效果-点击按钮变色
效果-增加过渡效果
完整代码如下
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<style>div{/* 过渡效果 */transition:.5s;overflow: hidden;}.div1{width: 100px;height: 10px;background-color: pink;}.div2{width: 100px;height: 100px;background-color: #f05922;}
</style>
<body><button onclick="change()">点击变色</button><div id="aaa" class="div1" index="1"><p>买买买</p><p>去结账</p></div>
</body>
<script>var div = document.querySelector('div')// getAttribute// console.log(div.getAttribute('id'));// console.log(div.getAttribute('class'));// console.log(div.getAttribute('index'));// setAttribute// div.setAttribute('id','bbb');// div.setAttribute('class','div2');// div.setAttribute('index','2');console.log(div.getAttribute('id'));console.log(div.getAttribute('class'));console.log(div.getAttribute('index'));function change(){if(div.getAttribute('class') == 'div1'){div.setAttribute('class','div2');}else{div.setAttribute('class','div1');}}</script>
</html>
解析:用到了两个操作属性
1、getAttribute获取属性
-
<style>.div1{width: 100px;height: 100px;background-color: pink;} </style> <body><div id="app" class="div1" index="1" ></div> </body> <script>var div = document.querySelector('div')console.log(div.getAttribute('id'));console.log(div.getAttribute('class'));console.log(div.getAttribute('index')); </script>
2、setAttribute修改属性
-
.div1{width: 100px;height: 100px;background-color: pink;}.div2{width: 100px;height: 100px;background-color: #dd5c25;} </style> <body><div id="app" class="div1" index="1" ></div> </body> <script>var div = document.querySelector('div')div.setAttribute('id','bbb')div.setAttribute('class','div2')div.setAttribute('index','2')console.log(div.getAttribute('id'));console.log(div.getAttribute('class'));console.log(div.getAttribute('index')); </script>