如何实现点击图片跳转超链接并在同一展示页仅显示被点击的图片
实现方案
完全可以实现,不需要给每张图片单独创建页面,用URL参数传值的方式就能搭建统一展示页,仅需编写首页+1个公共展示页即可。
第一步:改造首页图片链接
删除原代码中每张图片绑定独立页面的写法,所有图片的跳转链接都指向同一个统一展示页地址,同时把当前图片的资源路径、标题拼在URL后作为参数传递,改造后的首页示例代码:
<!-- 所有链接指向同一个统一展示页,此处命名为show.html --> <a href="show.html?img=Predators.jpg&title=Predators"> <img alt="Predators" src="Predators.jpg" width="180" height="180"> </a> <a href="show.html?img=Mercurial-Superfly.jpg&title=Mercurial Superfly"> <img alt="Mercurial Superfly" src="Mercurial-Superfly.jpg" width="180" height="180"> </a> <a href="show.html?img=99-gram-boots.jpg&title=99g"> <img alt="99g" src="99-gram-boots.jpg" width="180" height="180"> </a> <a href="show.html?img=Limited%20Edition%20Ronaldinho%20Tiempo.jpg&title=LimitedEditionTiempo"> <img alt="LimitedEditionTiempo" src="Limited Edition Ronaldinho Tiempo.jpg" width="180" height="180"> </a>
注意:如果图片文件名包含空格,需要把空格转义为
%20,避免URL识别错误。
第二步:编写统一展示页show.html
该页面仅需读取URL携带的参数,动态渲染对应图片即可,示例代码:
<!DOCTYPE html> <html> <head> <title>图片展示</title> <style> /* 可自定义展示样式,此处为居中显示的基础样式 */ body { display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #f5f5f5; } #showImg { max-width: 90%; max-height: 90vh; } </style> </head> <body> <img id="showImg" alt=""> <script> // 解析URL携带的参数 const urlParams = new URLSearchParams(window.location.search); const imgSrc = urlParams.get('img'); const imgTitle = urlParams.get('title'); // 动态给图片赋值 document.getElementById('showImg').src = imgSrc; document.getElementById('showImg').alt = imgTitle; document.title = imgTitle; </script> </body> </html>
效果说明
- 后续新增图片仅需在首页添加对应a标签和img标签,不需要新建任何独立页面
- 点击任意首页图片跳转后,展示页会自动读取对应参数,仅渲染用户点击的那张图片
- 纯原生HTML+JS实现,不需要引入任何第三方依赖
内容的提问来源于stack exchange,提问作者C.Sciana
相关产品推荐
相关产品推荐

