问题描述
我在DIV img
中有一个图像modal
,在右下角有一个按钮+
。此按钮调用函数imgfit()
,该函数将图像视图切换为“在窗口内居中对齐”或“ 100%”(即1:1像素)。它起作用,除了滚动条不允许我滚动图像的顶部/左侧:当以1:1观看时,图像在div内负移。
如何告诉滚动条它们“忘记”了图像的顶部/右侧?您可以看到问题here(使浏览器窗口相对较小,以便更好地查看问题)。
function imgfit()
{
if (fit) {
img.style.minWidth = "0px";
img.style.minHeight = "0px";
img.style.maxWidth = "100vw";
img.style.maxHeight = "100vh";
modal.style.overflow = "hidden"; // Prevent scroll of fullsize image
} else {
img.style.maxWidth = 'none';
img.style.maxHeight = 'none';
img.style.minWidth = img.naturalWidth+"px";
img.style.minHeight = img.naturalHeight+"px";
modal.style.overflow = "auto"; // Allow scroll of fullsize image
}
fit = ! fit;
}
这是图像的CSS
和模式div(如果我删除了align-items: center
和justify-content: center
,问题就消失了,但是图像没有居中):
.modal {
align-items: center;
justify-content: center;
position: fixed;
z-index: 100;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: #000;
-moz-user-select: none;
user-select: none;
touch-action: manipulation;
}
.img {
cursor: no-drop;
position: absolute;
margin: auto;
touch-action: manipulation;
}
解决方法
多亏了整洁的文章here(我不知道那个 sitepoint.com 网站),我解决了这个问题。罪魁祸首是position: absolute
。更改为display: grid
解决了该问题:
.modal {
display: grid;
align-items: center;
position: fixed;
z-index: 100;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: #000;
-moz-user-select: none;
user-select: none;
touch-action: manipulation;
}
.img {
grid-column: 1;
grid-row: 1;
cursor: no-drop;
margin: auto;
touch-action: manipulation;
}