给搜哈加了个更换背景功能
实现效果:
- 点击对应缩略图替换其为网页背景
- 上传图片替换其为网页背景
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
部分:
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);
});