给网页增加更换上传背景功能

2023-02-20 12:40:04 浏览数 (1)

实现效果:

  1. 点击对应缩略图替换其为网页背景
  2. 上传图片替换其为网页背景

HTML部分:

代码语言:html复制
<!--本地切换背景图-->
<img src="img/image1.jpg" id="image1" width="80" height="40" />
<img src="img/image2.jpg" id="image2" width="80" height="40" />
<img src="img/image3.jpg" id="image3" width="80" height="40" />

<!--上传按钮-->
<!--用<label> 绑定 <input> 标签,然后隐藏 <input>-->
<label for="uploadImage" class="uploadImage" ><strong>点击上传图片</strong></label>
<input type="file" name="image" value="" id="uploadImage" hidden="hidden"/>

JS部分:

代码语言:javascript复制
let images = ["img/image1.jpg", "img/image2.jpg", "img/image3.jpg"];
      let currentImageIndex = 0;
      document.body.style.backgroundImage = "url("   images[currentImageIndex]   ")";
      document.body.style.backgroundSize = "cover";  // 背景图片填充方式为覆盖
      // 点击缩略图切换
      document.getElementById("image1").addEventListener("click", function(){
        document.body.style.backgroundImage = "url("   images[0]   ")";
        document.body.style.backgroundSize = "cover";
      });
      document.getElementById("image2").addEventListener("click", function(){
        document.body.style.backgroundImage = "url("   images[1]   ")";
        document.body.style.backgroundSize = "cover";
      });
      document.getElementById("image3").addEventListener("click", function(){
        document.body.style.backgroundImage = "url("   images[2]   ")";
        document.body.style.backgroundSize = "cover";
      });
	  // 上传替换
      let uploadImage = document.getElementById("uploadImage");
      uploadImage.addEventListener("change", function(){
        let file = uploadImage.files[0];
        let reader = new FileReader();
        reader.onload = function(){
          let dataURL = reader.result;
          document.body.style.backgroundImage = "url("   dataURL   ")";
          document.body.style.backgroundSize = "cover";
        }
        reader.readAsDataURL(file);
      });

效果演示:搜哈-聚合搜索导航 右侧侧边栏

0 人点赞