根据上面的代码我需要在图片较小时点开放大后,图片置于悬浮窗中间,而非左上角
时间: 2024-04-15 19:31:53 浏览: 20
要将放大后的图片置于悬浮窗的中间位置,您可以使用`translate`属性来调整图片的位置。在悬浮窗中添加一个容器元素,然后将图片放置在容器元素中,并使用`translate`属性来使图片居中。
下面是修改后的代码示例:
```javascript
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 container = document.createElement("div");
container.style.display = "flex";
container.style.justifyContent = "center";
container.style.alignItems = "center";
container.style.height = "100%";
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})`;
};
container.appendChild(img);
popup.appendChild(container);
// 关闭悬浮窗
popup.onclick = function () {
document.body.removeChild(popup);
};
// 判断图片是否已经被点击过,如果是,则显示悬浮窗
if (img.getAttribute("data-clicked") === "true") {
document.body.appendChild(popup);
}
}
```
在上述代码中,我们添加了一个容器元素`container`来包裹图片`img`。通过为容器元素设置`display: flex`、`justifyContent: center`和`alignItems: center`,可以使图片在容器中居中显示。然后,我们将容器元素`container`添加到悬浮窗`popup`中。
这样,无论图片的大小如何,放大后的图片都会在悬浮窗的中间位置。
希望这次能满足您的需求!如有任何进一步的问题,请随时提问。