JS 切换效果

刚放假回家没什么事,便看了看JS,在原有代码上,加了个自动切换

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>JS切换效果</title>

        <style>
            body {
                background-color: #CCC;
            }
            
            .btn {
                width: 100px;
                height: 7px;
                background-color: white;
                margin: 10px;
                float: left;
            }
            
            .btn:first-of-type {
                background-color: #008B8B;
            }
            
            div[id^="div"] {
                width: 400px;
                height: 200px;
                clear: both;
                background-color: red;
                margin: 20px 0px;
                display: none;
            }
            
            #div1 {
                display: block;
            }
            
            #div2 {
                background-color: yellow;
            }
            
            #div3 {
                background-color: blue;
            }
        </style>
    </head>

    <body>
        <div class="btn" id="btn1" onmouseover="changeDiv(1)"></div>
        <div class="btn" id="btn2" onmouseover="changeDiv(2)"></div>
        <div class="btn" id="btn3" onmouseover="changeDiv(3)"></div>

        <div id="div1" class="div">
            div1
        </div>
        <div id="div2" class="div">
            div2
        </div>
        <div id="div3" class="div">
            div3
        </div>
        
        <script>
        var btn = document.getElementsByClassName("btn");
        var div = document.getElementsByClassName("div");
        var count = 0;
        setInterval(function(){
            for (var i=0;i<div.length;i++) {
                div[i].style.display = "none";
                btn[i].style.backgroundColor = "white";
            }
            div[count].style.display = "block";
            btn[count].style.backgroundColor = "#008B8B";
            count++;
            if(count == 3) count = 0;
        },1200);
        
        function changeDiv(id) {
            for (var i=0;i<div.length;i++) {
                div[i].style.display = "none";
                btn[i].style.backgroundColor = "white";
            }
            div[id-1].style.display = "block";
            btn[id-1].style.backgroundColor = "#008B8B";
        }
        </script>
    </body>
    <html>
原文地址:https://www.cnblogs.com/HRurl/p/7618011.html