1. 程式人生 > 其它 >JavaScript類名新增和移除

JavaScript類名新增和移除

<!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>

<body>
    <div style="width: 100%;">
        <div style="margin: 0 auto; padding: 0px; width: 520px; background-color: blanchedalmond;">
            <div style="display: flex;justify-content: center;">
                <img id="activeimg" style="margin-top: 20px;" src="./image/image01.jpg" width="420px" alt="">
            </div>
            <div id="imgGather"
                style="width: 100%; height: 100px; display: flex;justify-content: space-evenly;align-items: center;">
                <img class="firstimg" src="./image/image01.jpg" width="60px" alt="">
                <img src="./image/image02.jpg" width="60px" alt="">
                <img src="./image/image03.jpg" width="60px" alt="">
                <img src="./image/image04.jpg" width="60px" alt="">
                <img src="./image/image05.jpg" width="60px" alt="">

            </div>
        </div>
    </div>

    <style>
        #imgGather>.firstimg {
            border: 2px solid red;
        }
    </style>
      //classList屬性的方法有:
      //add(value) 新增類名,如果有則不新增
      //contains(value) 判斷是否存在類名,返回Boolean值
      //remove(value) 從列表中刪除類名
      //toggle(value) 切換類名:如果列表中存在則刪除,否則新增

    <script type="text/javascript">

        var activeimg = document.getElementById('activeimg');
        var imgGater = document.getElementById('imgGather');
        var allimg = document.getElementsByTagName('img');
        console.log(allimg)
        for (let i = 0; i < allimg.length; i++) {

            allimg[i].onmouseover = function () {
                for (let j = 0; j < allimg.length; j++) {
                      //classList.remove();可以實現移除任意一個class名。
                    allimg[j].classList.remove("firstimg");
                }
                console.log(allimg[i])
                //className可以實現新增任意一個class名。
                allimg[i] = this.className = 'firstimg';

            }
        }

    </script>

</body>

</html>