当前位置:网站首页>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思路其实差不多的,只需要清楚每次遍历的是哪个数组。
边栏推荐
- DSPE-PEG-Biotin, CAS: 385437-57-0, phospholipid-polyethylene glycol-biotin prolongs circulating half-life
- 哈希表基础
- Fluorescein-PEG-DSPE Phospholipid-Polyethylene Glycol-Fluorescein Fluorescent Phospholipid PEG Derivatives
- Webrtc从理论到实践一:初识
- Webrtc从理论到实践三:角色
- 一种用QT实现即时通信软件表情发送与接收的思路
- Introduction to CLS-PEG-FITC Fluorescein-PEG-CLS Cholesterol-PEG-Fluorescein
- a:自我介绍
- Unity版本升级问题总结
- 滑动窗口法
猜你喜欢
随机推荐
C语言对文件的操作(完整版)
Evaluating Machine Learning Models - Excerpt
关于Iframe
Unity版本升级问题总结
十分钟教你玩转分支语句!!!!!小白速进,新手福利!!
Software Testing Interview Questions 2021
5G的用途和工作原理
DSPE-PEG-Azide DSPE-PED-N3 Phospholipid-Polyethylene Glycol-Azide Lipid PFG
CAS:474922-22-0 Maleimide-PEG-DSPE Phospholipid-Polyethylene Glycol-Maleimide Brief Description
Wangeditor rich text editor to upload pictures and solve cross-domain problems
链表理论基础
DSPE-PEG-Azide DSPE-PED-N3 磷脂-聚乙二醇-叠氮脂质PFG
Cholesterol-PEG-Thiol CLS-PEG-SH Cholesterol-Polyethylene Glycol-Sulfhydryl
力扣151. 颠倒字符串中的单词
关于网络安全法的个人理解
【Rhapsody学习笔记】4:Relations
Webrtc从理论到实践二: 架构
Chemical Reagent Phospholipid-Polyethylene Glycol-Amino, DSPE-PEG-amine, CAS: 474922-26-4
Attention based ASR(LAS)
pyspark.ml feature transformation module