[英]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中之前立即预加载图像。 无论哪种情况,都必须先加载图像才能看到它们,因此无论如何都会有延迟。
如果您唯一要更改的是将img
的src
属性更改为本地文件夹,那么我认为对其他有效代码的唯一更改是images
数组中指向本地文件的字符串。
如果是这种情况,并且您想在不添加某种目录更改( ../
img/
之类)的情况下正确解析位置,则需要将这些图像与html文件放在同一目录中 ,不是file.js文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.