簡體   English   中英

JQuery - 預加載圖像(使用JQuery / native JavaScript / CSS)

[英]JQuery - Preload Images (using JQuery / native JavaScript / CSS)

我之前問過一個關於如何將鼠標懸停在小圖像上並將其他圖像加載到頁面右側的問題。 我有一切正常,但現在我想預先加載圖像

如何使用JQuery預加載圖像,以便我可以在需要時立即向用戶顯示(沒有加載時間)?

您可以非常輕松地預加載圖像,如下所示:

使用JQuery

function preloadImg(src) {
    $('<img/>')[0].src = src;
}

preloadImg('http://yoururl/to/the/picture.jpg');

原生Javascript

function preloadImg(src) {
    var img = new Image();
    img.src = src;
}

preloadImg('http://yoururl/to/the/picture.jpg');

使用CSS(不需要JavaScript)

您還可以使用CSS(和HTML)預加載圖像

CSS: div#preload { display: none; } div#preload { display: none; }

HTML:

<div id="preload">
   <img src="http://yoururl/to/the/picture1.jpg" width="1" height="1" alt="Image 1" />
   <img src="http://yoururl/to/the/picture2.jpg" width="1" height="1" alt="Image 2" />
   <img src="http://yoururl/to/the/picture3.jpg" width="1" height="1" alt="Image 3" />
</div>

預加載圖像的最簡單方法是這樣的:

function preload(selector, url) {
    $('<img/>').attr({
        src: url,
        height: '1px',
        width: '1px'
    }).appendTo($(selector)).delay(1000).remove();
}

我是這樣做的。

我查找任何懸停狀態圖像然后通過用-hv(懸停)替換-nm(正常)預加載懸停狀態

這樣做的好處在於沒有URL的硬編碼

$(function() {
        $(this).find("img[src*='-nm']").each(function () {
           $('<img/>')[0].src = this.src.replace(/-nm/, "-hv");
        });
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM