function showPopup(src) { var popup = document.createElement("div"); popup.style.position = "fixed"; popup.style.top = "50%"; popup.style.left = "50%"; popup.style.transform = "translate(-50%, -50%)"; popup.style.backgroundColor = "rgba(0, 0, 0, 0.8)"; popup.style.zIndex = "9999"; popup.style.width = "75%"; // 设置悬浮窗宽度为页面宽度的75% popup.style.height = "75%"; // 设置悬浮窗高度为页面高度的75% var img = document.createElement("img"); img.src = src; img.alt = "放大照片"; img.style.maxWidth = "100%"; img.style.maxHeight = "100%"; var scale = 1; // 初始缩放比例 var scaleFactor = 0.1; // 每次滚动的缩放因子 // 鼠标滚轮事件 img.onwheel = function (e) { e.preventDefault(); // 阻止默认滚轮行为处理页面滚动 scale += e.deltaY > 0 ? -scaleFactor : scaleFactor; // 根据滚轮滚动方向确定缩放比例 scale = Math.max(scale, 0.1); // 最小缩放比例为0.1 img.style.transform = `scale(${scale})`; }; popup.appendChild(img); // 关闭悬浮窗 popup.onclick = function () { document.body.removeChild(popup); }; document.body.appendChild(popup); }我只需要在点击放大图片时才显示悬浮窗,添加图片时不需要显示悬浮窗,
时间: 2024-04-15 21:32:03 浏览: 237
明白了您的需求。根据您的要求,在仅点击放大图片时显示悬浮窗的逻辑,我们可以将悬浮窗的创建和显示逻辑放到`img.onclick`事件处理函数中。
下面是修改后的代码示例:
```javascript
function showPopup(src) {
var img = document.createElement("img");
img.src = src;
img.alt = "放大照片";
img.style.maxWidth = "100%";
img.style.maxHeight = "100%";
var scale = 1; // 初始缩放比例
var scaleFactor = 0.1; // 每次滚动的缩放因子
// 鼠标滚轮事件
img.onwheel = function (e) {
e.preventDefault(); // 阻止默认滚轮行为处理页面滚动
scale += e.deltaY > 0 ? -scaleFactor : scaleFactor; // 根据滚轮滚动方向确定缩放比例
scale = Math.max(scale, 0.1); // 最小缩放比例为0.1
img.style.transform = `scale(${scale})`;
};
// 点击放大图片时显示悬浮窗
img.onclick = function () {
var popup = document.createElement("div");
popup.style.position = "fixed";
popup.style.top = "50%";
popup.style.left = "50%";
popup.style.transform = "translate(-50%, -50%)";
popup.style.backgroundColor = "rgba(0, 0, 0, 0.8)";
popup.style.zIndex = "9999";
popup.style.width = "75%"; // 设置悬浮窗宽度为页面宽度的75%
popup.style.height = "75%"; // 设置悬浮窗高度为页面高度的75%
var zoomedImg = document.createElement("img");
zoomedImg.src = src;
zoomedImg.alt = "放大照片";
zoomedImg.style.maxWidth = "100%";
zoomedImg.style.maxHeight = "100%";
var scale = 1; // 初始缩放比例
var scaleFactor = 0.1; // 每次滚动的缩放因子
// 鼠标滚轮事件
zoomedImg.onwheel = function (e) {
e.preventDefault(); // 阻止默认滚轮行为处理页面滚动
scale += e.deltaY > 0 ? -scaleFactor : scaleFactor; // 根据滚轮滚动方向确定缩放比例
scale = Math.max(scale, 0.1); // 最小缩放比例为0.1
zoomedImg.style.transform = `scale(${scale})`;
};
popup.appendChild(zoomedImg);
// 关闭悬浮窗
popup.onclick = function () {
document.body.removeChild(popup);
};
document.body.appendChild(popup);
};
// 隐藏原始的input元素
img.style.display = "none";
// 添加图片到input元素的父节点
img.parentNode.appendChild(img);
}
```
在上述代码中,我们将创建悬浮窗的逻辑移动到了`img.onclick`事件处理函数中。这样,只有在点击放大图片时,才会创建和显示悬浮窗。
希望这次修改能满足您的需求!如有任何进一步的问题,请随时提问。
阅读全文
相关推荐












