设置img标签CSS display为inline的JS函数失效问题排查
问题:点击通用水果图片后,6张替换图片未显示
你的代码核心问题出在expand()函数的元素获取逻辑上,原写法无法正确拿到.Fruits类下的图片元素,导致替换图片始终不显示。
错误点分析
- 错误写法:
var fruit = document.getElementsByTagName("fruit_all[0].img"),这不是合法的DOM选择器语法,getElementsByTagName仅能接收标签名(比如'img'),不能传入变量表达式。 - 循环变量
j未声明,会成为全局变量,可能引发意外问题。
修复方案
- 正确获取
.Fruits容器内的所有img元素,可使用document.querySelectorAll('.Fruits img')(更简洁的现代写法),或fruit_all[0].getElementsByTagName('img') - 用
let声明循环变量j,避免全局变量污染 - 调整
.Fruits的样式,用Grid布局实现每行3张图片的效果,比inline布局更整齐可控
修复后的完整代码
<!DOCTYPE html> <html> <head> <style> .Fruits { display: grid; grid-template-columns: repeat(3, 100px); gap: 10px; } .Fruits img { border: 6px solid blue; width: 100px; height: 100px; cursor: pointer; display: none; } img { border: 6px solid blue; width: 100px; height: 100px; cursor: pointer; } </style> </head> <body> <script> function expand() { // 获取.Fruits容器下的所有img元素 var fruit = document.querySelectorAll('.Fruits img'); for (let j = 0; j < fruit.length; j++) { fruit[j].style.display = 'block'; } // 隐藏初始的通用水果图片 document.getElementsByTagName("img")[0].style.display = 'none'; } </script> <h1>Fruit</h1> <!--Generic Fruits image--> <img src="https://wpcdn.us-east-1.vip.tn-cloud.net/www.hawaiimagazine.com/content/uploads/2020/12/exoticfruits-opener.jpg" height="100" width="100" onclick="expand()"> <!--This is what replaces the Generic Fruits image--> <div class="Fruits"> <img src="https://foodprint.org/wp-content/uploads/2018/10/IMG_3392-e1539129880189.jpg" height="100" width="100"> <img src="https://foodprint.org/wp-content/uploads/2018/10/imageedit_127_5581342771.jpg" height="100" width="100"> <img src="https://i0.wp.com/moodymoons.com/wp-content/uploads/2016/02/img_8986.jpg?fit=4560%2C3000&ssl=1" height="100" width="100"> <img src="https://www.naturalhealth365.com/wp-content/uploads/2016/04/blueberries.jpg" height="100" width="100"> <img src="https://th.bing.com/th/id/OIP.gBifOTB-F-wBTx3bzYPiGgHaE-?pid=ImgDet&rs=1" height="100" width="100"> <img src="https://th.bing.com/th/id/OIP.3yrzbKoKIgyR7eBhHma26AHaGm?pid=ImgDet&rs=1" height="100" width="100"> </div> </body> </html>
补充说明
grid-template-columns: repeat(3, 100px)可自动让图片每行排列3张,超出后自动换行- 把图片的
display设为block,配合Grid布局的gap属性,能让图片之间保持均匀间距,视觉效果更整洁
内容的提问来源于stack exchange,提问作者Diamoniner12345
相关产品推荐
相关产品推荐

