classList用法


<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>classList</title>
        <style type="text/css">
            .box{
                width: 100px;
                height: 100px;
                margin: 10px 0;
                background-color: blue;
            }
            .red{
                background-color: red;
            }
        </style>
    </head>
    <body>
        <div class="box"></div>
        <div class="box"></div>
        <script type="text/javascript">
      /*classList:獲取class列表屬性
        length class的長度
        add() 添加class方法
        remove() 刪除class方法
        toggle() 切換class方法
      */
var box = document.querySelectorAll('.box'); /*for (var i = 0; i < box.length; i++) { box[i].isChecked = false; box[i].onclick = function () { if (this.isChecked) { this.className = 'box'; } else { this.className = 'box red'; } this.isChecked = !this.isChecked; } }*/ /*for (var i = 0; i < box.length; i++) { box[i].isChecked = false; box[i].onclick = function () { console.dir(this); if (this.isChecked) { this.classList.remove('red'); } else { this.classList.add('red'); } this.isChecked = !this.isChecked; } }*/ // 三目寫法 for (var i = 0; i < box.length; i++) { box[i].isChecked = false; box[i].onclick = function () { console.dir(this); /*if (this.isChecked) { this.classList.remove('red'); } else { this.classList.add('red'); }*/ // this.isChecked ? this.classList.remove('red') : this.classList.add('red'); this.classList[this.isChecked?'remove':'add']('red'); this.isChecked = !this.isChecked; } } </script> </body> </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM