簡體   English   中英

如何在本地的javascript變量中加載圖像

[英]how to load images in a javascript variable locally

我在用網站的jquery制作的背景旋轉木馬方面獲得了幫助,但效果很好。.除了我發現頁面最初需要花費一些時間來加載。。對於背景,而不是通過“ http://www.whatever.jpg ”加載它們,該頁面可能加載得更快。.但是我還是有點菜鳥..而且還無法弄清楚為什么這樣做無法正常工作。這是我的代碼:

var images = [
//even though I downloaded the picture and its in the same folder as this file.js, the background just loads a black page, then the other 2 load fine.
"bg1-orig.jpg",
"http://www.desktopaper.com/wp-content/uploads/Cool-Hd-Wallpapers-2.jpg",
"http://wallpaperscraft.com/image/restaurant_table_interior_modern_style_39288_1920x1080.jpg"
];

var $body = $("body"),
$bg = $("#bg"),
n = images.length,
c = 0; // Loop Counter
num = 200;

// Preload Array of images...
for(var i=0; i<n; i++){
var tImg = new Image();
tImg.src = images[i];
}

$body.css({backgroundImage : "url("+images[c]+")"});

(function loopBg(){
  $bg.hide().css({backgroundImage : "url("+images[++c%n]+")"}).delay(7000).fadeTo(2200, 1,      function(){
$body.css({backgroundImage : "url("+images[c%n]+")"}); 
loopBg();
});
}());

我已經搜索了一段時間...感謝您的幫助!

您不希望嘗試在將圖像加載到CSS中之前立即預加載圖像。 無論哪種情況,都必須先加載圖像才能看到它們,因此無論如何都會有延遲。

如果您唯一要更改的是將imgsrc屬性更改為本地文件夾,那么我認為對其他有效代碼的唯一更改是images數組中指向本地文件的字符串。

如果是這種情況,並且您想在不添加某種目錄更改( ../ img/之類)的情況下正確解析位置,則需要將這些圖像與html文件放在同一目錄 ,不是file.js文件。

暫無
暫無

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

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