点击图片放大/还原功能仅对首张图片生效,如何实现所有图片支持该功能?
点击图片放大/还原功能仅对首张图片生效,如何实现所有图片支持该功能?
嗨,这个问题很好解决,我来给你捋捋原因和解决方案~
问题根源
你当前的JavaScript代码里用了 document.querySelector('.img-responsive'),这个方法的特性是只返回页面中第一个匹配到的元素,所以只有第一张图片被绑定了点击事件,后面的图片自然没反应啦。
解决方案
我们需要选中所有带有 .img-responsive 类的图片,然后给每一张都绑定点击事件。用 document.querySelectorAll('.img-responsive') 就能获取到所有匹配的图片元素,它会返回一个元素集合(NodeList),接着用 forEach 遍历这个集合,给每个元素单独添加点击监听即可。
另外,你HTML里图片的 onclick="enlargeImg()" 属性其实可以删掉了,因为我们已经通过事件监听绑定了功能,这样代码更整洁。
修改后的JavaScript代码如下:
document.querySelectorAll('.img-responsive').forEach(img => { img.addEventListener('click', function(){ this.classList.toggle('enlarged'); }); });
完整修改后的代码片段(重点看script部分)
<?php include('header.php'); ?> <style> table, th, td { border: 1px solid black; padding: 45px; } table { border-spacing: 25px; } .center { margin-left: auto; margin-right: auto; } .pagination { display: inline-block; } .pagination a { color: black; float: left; padding: 8px 16px; text-decoration: none; transition: background-color .3s; border: 1px solid #ddd; } .pagination a.active { background-color: #4CAF50; color: white; border: 1px solid #4CAF50; } .pagination a:hover:not(.active) {background-color: #ddd;} </style> <style> .img-responsive { transition: all 0.25s ease } .enlarged { transform: scale(1.3); } </style> <?php $enlarged=false; ?> <div class="container text-center"> <table class="center" style="font-family:'Lato', 'Courier', 'monospace'" width="100%" height="100%" border="1"> <tr> <td align="center" valign="middle"><img class="img-responsive" style="max-width:400px;width:100%" height="auto" src="xyz1.jpg" id="img1" /><br/> </td> </tr> <tr> <td align="center" valign="middle"><img class="img-responsive" style="max-width:400px;width:100%" height="auto" src="xyz2.jpg" id="img2" /><br/> </td> </tr> </table><br/><br/> </div> <p></p> <script> document.querySelectorAll('.img-responsive').forEach(img => { img.addEventListener('click', function(){ this.classList.toggle('enlarged'); }); }); </script> </body></html>
这样修改后,每一张带有 .img-responsive 类的图片点击后都会切换放大/还原状态啦~
备注:内容来源于stack exchange,提问作者Ron
相关产品推荐
相关产品推荐

