JavaScript-换肤效果(换背景)

换肤效果:点击不同图片,更换相应页面背景

实现思路

  1. 定义一组图片,每个src属性赋值背景图片路径
  2. 获取一组图片元素对象(得到伪数组)
  3. for循环给图片绑定点击事件- - -onclick,事件处理程序中设置body元素对象的背景图片为- - -当前被点击的图片的路径
  4. 注意:body元素对象的获取为- - -document.body,js为背景图片路径赋值注意路径的拼接- - -document.body.style.backgroundImage = ‘url(’ + this.src + ‘)’;

代码示例:

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>换肤效果title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background: url(images/壁纸1.jpg) no-repeat center top;
            background-size: cover;
        }
        
        .box {
            overflow: hidden;
            width: 610px;
            margin: 100px auto;
            background-color: #fff;
        }
        
        .box li {
            width: 25%;
            height: 100px;
            list-style: none;
            float: left;
            cursor: pointer;
            border: 1px solid #fff;
        }
        
        img {
            width: 100%;
            height: 100%;
        }
    style>
head>

<body>
    <ul class="box">
        <li><img src="images/壁纸1.jpg" alt="">li>
        <li><img src="images/壁纸2.jpg" alt="">li>
        <li><img src="images/壁纸3.jpg" alt="">li>
        <li><img src="images/壁纸4.jpg" alt="">li>
    ul>
    <script>
        var pics = document.querySelector('.box').querySelectorAll('img');
        console.log(pics);
        for (var i = 0; i < pics.length; i++) {
            pics[i].onclick = function() {
                console.log(this.src);
                document.body.style.backgroundImage = 'url(' + this.src + ')';
            }
        }
    script>
body>

html>

页面效果:

你可能感兴趣的:(前端,javascript,html,css,前端)