在加載時,如果瀏覽器寬度大于 540 像素,則包含影像的模式將被切斷(見下圖)。我該怎么做才能使垂直滾動條立即出現?

我正在處理的這個現有專案正在使用tingle modal plugin。它是這樣鏈接的:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="tingle.min.css">
<style>
html, body {
height: 100%;
}
img {
height: auto;
width: 100%;
}
</style>
<title>Tingle Modal</title>
</head>
<body>
<script src="tingle.min.js"></script>
<script src="modal.js"></script>
</body>
</html>
modal.js 是我創建包含影像的模態的地方:
function createModal(content) {
let $modal = new tingle.modal({
footer: false,
stickyFooter: false,
closeMethods: ["overlay", "button", "escape"],
closeLabel: "Close",
cssClass: ["modal"],
beforeClose: function() {
return true; // close the modal
},
onClose: function() {
$modal.destroy();
}
});
$modal.setContent(content);
$modal.open();
}
createModal("<div id='modal'><img id='sample' src='sample.jpg' /></div>");
console.log(document.getElementById("sample").offsetHeight);
我注意到當您放大或縮小或調整瀏覽器大小時,我會得到預期的滾動條行為。我還注意到在加載時,影像高度為 0。我無法將影像高度設定為像素值,因為我將有幾個包含大小不同的不同影像的模式。
您還可以在此處查看行為:CodeSandbox。請先使 CodeSandbox 中嵌入的瀏覽器寬度變大,然后重繪 以了解我的意思。
我嘗試了以下方法。但是即使整個模態適合 100vh,它也會添加滾動條,這是不可取的。
.tingle-modal {
overflow-y: scroll;
}
uj5u.com熱心網友回復:
嘗試添加這些樣式
.tingle-modal {
overflow-y: auto;
}
如果需要保存關閉按鈕的位置,則添加:
.tingle-modal__close {
position: sticky;
align-self: end;
}
而不是
createModal("<div id='modal'><img src='sample.jpg' /></div>");
用它
const img = new Image();
img.onload = () => {
createModal("<div id='modal'><img src='sample.jpg' /></div>");
};
img.src = "sample.jpg";
uj5u.com熱心網友回復:
我查看了中的代碼tingle.min.js。它檢查模態的高度是否溢位,如果是,則添加一個tingle-modal--overflow類。但是,當檢查高度時,影像尚未加載。所以我不得不在呼叫createModal函式后重做檢查,如下所示:
document.getElementsByTagName("img")[0].onload = function() {
const $modal = document.getElementsByClassName("tingle-modal")[0];
if (window.innerHeight <= $modal.clientHeight)
$modal.classList.add("tingle-modal--overflow");
};
這是解決方案的 jQuery 版本:
$(".tingle-modal-box img").on("load", function() {
const $modal = $(".tingle-modal");
if (window.innerHeight <= $modal.height())
$modal.addClass("tingle-modal--overflow");
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332949.html
標籤:javascript html css 图片 滚动条
