其他分享
首页 > 其他分享> > js 图片切换

js 图片切换

作者:互联网

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        .focus {
            position: relative;
            width: 300px;
            height: 300px;
            border: 5px solid blue;
            margin: 50px auto;
        }

        .focus img {
            position: absolute;
            top: 0;
            left: 0
        }

        .focus p {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 30px;
            line-height: 30px;
            text-align: center;
        }

        .focus span {
            display: inline-block;
            width: 20px;
            height: 20px;
            background: blue;
            color: #fff;
            line-height: 20px;
            cursor: pointer;
        }

        .focus span.active {
            background: red;
        }

        .focus h2 {
            z-index: 11;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            background: rgba(255, 0, 0, 0.5);
            font-size: 16px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            color: #fff;
        }
    </style>
    <div class="focus" id="focus">
        <!-- 标题 -->
        <h2>狗子1</h2>
        <img src="./img/1.jpg" width="300" height="300" />
        <p>
            <span class="active">1</span>
            <span>2</span>
            <span>3</span>
            <span>4</span>
        </p>
    </div>
    <script>
        //点击不同的序号  让图片切换到对应的图片 将标题也切换为对应的标题  让点击的序号亮起,其他序号灭掉
        var title = document.getElementsByTagName("h2")[0];
        var img = document.getElementsByTagName("img")[0];
        var spans = document.getElementsByTagName('span');

        //声明一个记录图片路径的数组
        var imgArr = [
                        "./img/1.jpg",
                        "./img/2.jpg",
                        "./img/3.jpg",
                        "./img/4.jpg"
                     ]
        //1.点击序号 切换对应图片
        for(var i=0; i<spans.length; i++){
            spans[i].idx = i;
            spans[i].onclick = function(){
                // 切换对应图片
                img.src = imgArr[this.idx];
                //切换标题
                title.innerText = "狗子"+(this.idx+1);
                //让当前点击的span亮起  其他span灭掉  排他思想
                //干掉所有人
                for(var j=0; j<spans.length; j++){
                    spans[j].className = "";
                }
                this.className = "active";
            }
        }

    </script>
</body>

</html>

标签:span,img,focus,jpg,height,切换,var,js,图片
来源: https://blog.csdn.net/weixin_45735694/article/details/122550810