我有一個顯示用戶資料的頁面,例如他們的影像(個人、學習等)。
為了顯示影像,我有一個 Modal。它有一個img
標簽。
網站管理員,點擊鏈接,網站為他打開一個Modal。
但是只有1個Modal和1個 img
標簽!
經理點擊一位用戶的個人照片。瀏覽器加載圖片并將其顯示到模態中。
經理關閉模態并打開同一用戶的學士學位照片。瀏覽器先打開同一張Modal(包含上一張圖片)然后加載新圖片!!!
經理看了一會兒之前的圖片,我認為這會給所有用戶帶來不好的體驗,尤其是網路速度較慢的用戶。
模態,由 JS 打開。那么我怎樣才能確保圖片已經加載到之后打開模態呢?
我真的需要它。有什么想法嗎?
(我也使用 jQuery。)
uj5u.com熱心網友回復:
一種方法是給他們一個給他們 opacity: 0 所以他們不顯示的類:
<img src="/path/to/image" class="loading">
在 CSS 中:
.loading {
opacity: 0;
}
在頭部,如果 JavaScript 被禁用,我們會覆寫它(所以我們對非 JavaScript 訪問者并不友好:
<noscript>
<style>
.loading {
opacity: 1;
}
</style>
</noscript>
...然后在頁面底部的代碼中,找到所有影像并在加載后洗掉該類
(function() {
// Get an array of the images
var images = Array.prototype.slice.call(document.querySelectorAll("img.loading"));
// Hook their load and error events, even though they may have already fired
images.forEach(function(image) {
image.addEventListener("load", imageDone.bind(null, image));
image.addEventListener("error", imageDone.bind(null, image)); // Could handle errors differently
});
// Check to see if any images are already complete
checkImages();
function imageDone(img) {
img.classList.loading("remove");
images = images.filter(function(entry) { entry != img });
}
function checkImages() {
images.forEach(function(image) {
if (image.complete) {
imageDone(image);
}
});
if (images.length) {
// Check back in a second
setTimeout(checkImages, 1000);
}
}
})();
這是一種束手無策的方法。它主動檢查影像是否已完成加載,并反應性地處理影像的加載和錯誤事件。從理論上講,我們不應該需要 setTimeout,并且您可以在沒有它的情況下進行測驗,但是......
請注意,一旦影像完成,我們將洗掉該類以使其可見。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493551.html
標籤:javascript html jQuery 图片 模态对话
上一篇:Node.js:[ERR_INVALID_ARG_TYPE]:“資料”引數必須是字串型別或Buffer、TypedArray或DataView的實體。收到未定義
下一篇:如何在塊中顯示影像?