AI 摘要
生成中...
index.html
<body>
<div class="right">
<label for="bg">更换背景</label>
<input class="bg-ipt" type="file" id="bg" />
</div>
</body>index.js
document.querySelector('.bg-ipt').addEventListener('change', (e) => {
// 1.选择图片上传,设置body背景
//console.log(e.target.files[0]);
const fd = new FormData()
fd.append('img', e.target.files[0])
axios({
url: 'http://hmajax.itheima.net/api/uploadimg',
method: 'POST',
data: fd,
}).then((res) => {
console.log(res.data)
const imgUrl = res.data.data.url
document.body.style.backgroundImage = `url("${imgUrl}")`
// 2.图片上传成功时,保存图片URL网址到本地
localStorage.setItem('bgImg', imgUrl)
})
})
// 3.网页运行后,从本地获取图片的URL网址使用
const bgUrl = localStorage.getItem('bgImg')
// 本地有背景图的地址才设置
bgUrl && (document.body.style.backgroundImage = `url("${bgUrl}")`)