• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

JavaScript类名添加和移除

开发技术 开发技术 5小时前 1次浏览
<!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>

程序员灯塔
转载请注明原文链接:JavaScript类名添加和移除
喜欢 (0)