html -使图像成为鼠标点击的背景图像?[已关闭]

sxpgvts3  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(144)

已关闭,此问题需要更focused。它目前不接受回答。
**想改善这个问题吗?**更新问题,使其只关注editing this post的一个问题。

关闭7天前。
Improve this question
我没有任何代码,因为我完全卡住了,不知道从哪里开始。这个概念很简单-我希望能够点击一个图像(从其他几个在网页上),并有它成为页面的背景图像。
我知道我需要JavaScript来做这件事,但我不知道从哪里开始。
我本来打算在JavaScript中指定一个数组来进行选择,但是我不确定如何指定被单击的特定图像的输入将改变背景图像。

j8ag8udp

j8ag8udp1#

您可以为img元素创建click处理程序,这将设置document.body的正确style属性:

for (let img of document.querySelectorAll("img")) {
    img.addEventListener("click", function() {
        document.body.style.backgroundImage = `url('${this.src}')`;
        document.body.style.backgroundRepeat = "no-repeat";
        document.body.style.backgroundSize = "cover";
    })
}
<img src="https://th.bing.com/th/id/OIP.wwxK07x0Umfnh0l-nrjxjgHaDg?pid=ImgDet&rs=1">
<img src="https://www.forestis.it/media/1064/forestis-see-idm.jpg?mode=max&rnd=132197836980000000">

相关问题