实现百度换肤的效果

201 阅读1分钟

这是整个代码,包括了样式设置,可以只关注下body的背景设置即可,该功能的实现主要是依靠获取元素属性,然后进行body.style.backgroundImage的赋值,运用到了点击onclick事件,描述过程,就是点击li的时候,就可以选择不同的背景图片啦,挺好看的,重点是js部分哈

```<!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>
        body{
            background:no-repeat;
            background-size: 100%;
            background-image:url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1113%2F052420110515%2F200524110515-2-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653539537&t=9fca0626faf408b6ed5bbe01c4550bce);
           
        }
        li{
            width: 100px;
            height: 100px;
            float: left;
        }
        img{
            width: 100px;
            height: 100px;
        }
    </style>
</head>
<body>
    <ul>
        <li><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp03%2F1Z92210320C612-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653539537&t=56f85d4583c5661b5f590c636b367aaf" alt=""> </li>
        <li><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1114%2F113020142315%2F201130142315-1-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653539537&t=049d5c4731dfee20487c0fd4a7a79dc2" alt=""> </li>
        <li><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp03%2F1Z921104Z92S8-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653539537&t=339983720d23503cbab585037f28e2c1" alt=""> </li>
    </ul>
    <script>
        var liEle=document.querySelectorAll('li')
        var body=document.body
        for(var i=0;i<liEle.length;i++ ){
            liEle[i].onclick=function(){
             var src= this.firstElementChild.getAttribute("src")
             body.style.backgroundImage='url('+src+')'
            
            }
        }
    </script>
</body>
</html>

效果图:

![image.png](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5cf3e571e35e4b13b130308019dae3e1~tplv-k3u1fbpfcp-watermark.image?)