使用jQuery实现点击图片弹出放大效果,无报错但无响应如何排查
存在的问题
- HTML类名格式错误:多个类名需用空格分隔,不能加逗号,同时原img标签携带
img-popup类会和后续创建的弹出层类产生冲突 - img为自闭合空元素,不支持在内部插入子元素,
insertAdjacentElement("beforeend", Popup)属于无效操作 Popup.innerHTML = this写法错误:this是img DOM对象,直接赋值给innerHTML只会输出[object HTMLImageElement]文本,无法渲染图片- 弹出层CSS配置错误:
position: relative无法实现悬浮弹出效果,缺少居中、层级、遮罩相关配置
修正后可运行代码
HTML代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <figure> <img class="double img-thumbnail" src="https://via.placeholder.com/200" alt="Poodle" title="View larger image..." /> <figcaption class="caption1">Standard Poodle</figcaption> </figure>
CSS代码
/* 弹出层遮罩 */ .img-popup { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.8); display: flex; align-items: center; justify-content: center; z-index: 999; cursor: zoom-out; } /* 弹出的大图样式 */ .img-popup img { max-width: 80%; max-height: 80%; border: 3px groove #fff; }
JS代码
$(document).ready(function() { $(".img-thumbnail").on("click", function() { // 创建弹出层 const Popup = document.createElement("div"); Popup.className = "img-popup"; // 复用当前点击图片的资源创建大图 const largeImg = document.createElement("img"); largeImg.src = this.src; largeImg.alt = this.alt; Popup.appendChild(largeImg); // 弹出层插入全局body中 document.body.appendChild(Popup); // 点击弹出层任意位置关闭 Popup.addEventListener('click', () => Popup.remove()); }); });
内容的提问来源于stack exchange,提问作者Khansa Sofia
相关产品推荐
相关产品推荐

