其他分享
首页 > 其他分享> > 原生js实现点击后给body换肤

原生js实现点击后给body换肤

作者:互联网

在这里插入图片描述

<!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>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            background: no-repeat;
            background-size: 100%;
        }

        div {
            background-color: pink;
            display: none;
        }

        img {
            width: 200px;
            height: 200px;
            margin: 100px;
        }
    </style>

</head>

<body>
    <div></div>
    <button id="btn">切换</button>
    <script>
        var imgArr = [
            'images/1.jpg',
            'images/2.jpg',
            'images/3.jpg'
        ];
        var btn = document.getElementById('btn');
        var div = document.querySelector('div');
        var img = document.getElementsByTagName('img');
        for (var i = 0; i < imgArr.length; i++) {
            var img = document.createElement('img');
            img.src = imgArr[i];
            div.appendChild(img);
        }
        btn.onclick = (e) => {
            var e = window.event || e;
            div.style.display = "none" ? "block" : "none";
            e.stopPropagation();
        }
        var img = document.getElementsByTagName('img');
        //var j的话,当程序执行完整个循环j=5;  let j 出了{}j会报错
        for (let j = 0; j < img.length; j++) {
            img[j].onclick = () => {
                document.body.style.backgroundImage = "url(" + imgArr[j] + ")";
                div.style.display = "none";
            }
        }
        document.onclick = () => {
            div.style.display = "none";
        }
    </script>
</body>

</html>

标签:换肤,body,none,img,style,js,var,div,document
来源: https://blog.csdn.net/vxx_xx/article/details/119486044