当前位置:网站首页>DOM操作-案例:切换背景图片
DOM操作-案例:切换背景图片
2022-07-31 05:18:00 【春意迟迟、】
要求:有几张供选择的图片,点击哪张图片,哪张图片就作为背景图片
写代码之前先来分析思路:
- 获取页面上的图片,把它们保存到数组中
- 遍历保存图片的数组,为每个图片添加点击事件
- 点击时间里面就是写:把点击的图片作为背景图
<body> <style> img { width: 100px; height: 100px; } </style> <img src="../picture/玫瑰.webp" alt="" class="img1"> <img src="../picture/粉色的云.webp" alt="" class="img2"> <img src="../picture/草原.webp" alt="" class="img3"> </body> <script> //可以用for循环实现 var imgs = document.querySelectorAll("img") console.log(imgs) //遍历保存图片的类数组 for (let i = 0; i < imgs.length; i++) { //为每个图片绑定点击事件 imgs[i].onclick = function fn() { //${}取值 document.body.style.backgroundImage = `url("${imgs[i].src}")` document.body.style.backgroundRepeat = "no-repeat" } } </script><script> //也可以用forEach循环实现 var imgs = document.querySelectorAll("img") imgs.forEach((el) => { //el是imgs里面的元素,也就是每张图片 el.onclick = function fn() { document.body.style.backgroundImage = `url("${el.src}")` document.body.style.backgroundRepeat = "no-repeat" } }) </script>结果展示:
用for循环和forEach思路其实差不多的,只需要清楚每次遍历的是哪个数组。
边栏推荐
猜你喜欢

Fluorescein-PEG-DSPE Phospholipid-Polyethylene Glycol-Fluorescein Fluorescent Phospholipid PEG Derivatives

日志jar包冲突,及其解决方法

Learn how to get a database connection with JDBC

力扣刷题之排序链表

911崩了,自养号测评环境IP有哪些更好的选择

什么样的人不适合入行编程?你真的适合学习编程吗?

Unity Text一个简单的输入特效

力扣.两数之和/四数相加||

Log jar package conflict, and its solution

一种用QT实现即时通信软件表情发送与接收的思路
随机推荐
Redis-Hash
Software Testing Interview Questions 2021
Picture-in-Picture API in the browser
【Latex】TexLive+VScode+SumatraPDF 配置LaTex编辑环境
解决nx安装 jtop问题
Natural language processing related list
2021-09-30
Data Preprocessing, Feature Engineering, and Feature Learning - Excerpt
Shell/Vim related list
Unity版本升级问题总结
pyspark.ml feature transformation module
C语言对文件的操作(完整版)
UR3机器人运动学分析之逆运动学分析
5G的用途和工作原理
物联网时代网络安全成第一大关
Unity软件中UGUI和NGUI的多语言开发
Webrtc从理论到实践一:初识
box-shadow相关属性
Remote file xxx is mapped to the local path xxx and can't be found. You can continue debugging....
MySQL free installation download and configuration tutorial

