(八)原生js案例之图片轮播显示设置背景

图片轮播,看到自己喜欢的壁纸,进行选择设置

效果

请添加图片描述

实现代码

  • 必要的css
* {
      margin: 0;
      padding: 0;
    }

    body {
      height: 100vh;
      overflow: hidden;
    }

    #box {
      width: 800px;
      height: 400px;
      border: 1px solid #ccc;
      margin: 60px auto 20px;
    }
  • 静态页面
<div id="box">
   
  </div>
  <ul id="list" class="order-list d-flex justify-content-center">
    <li class="list-group-item d-flex align-items-center">
      <button type="button" class="btn btn-primary mx-2">图片播放</button>
      <button type="button" class="btn btn-danger mx-2">选择确认</button>
    </li>
  </ul>
  • 核心代码
window.onload = function () {
      const oBtn = document.querySelectorAll('button');
      const picArr = ['./images/1.png', './images/2.png', './images/3.png'];
      const oBody = document.body;
      const oBox = document.getElementById('box');
      let index = 0, timer = null;

      oBtn[0].onclick = function () {
        clearInterval(timer);
        //定时更换背景图片
        function changeBg() {
          //实现图片循环切换
          index = index % 3
          oBox.index = index
          oBox.style.background = `url(${picArr[index]}) no-repeat center center`;
          index++;
        }
        timer = setInterval(changeBg, 1000)
      }

      //取消定时器
      oBtn[1].onclick = function () {
        clearInterval(timer);
        oBody.style.background = `url(${picArr[oBox.index]}) no-repeat center center`;
      }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值