简体   繁体   English

如何在本地的javascript变量中加载图像

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

I had help with this background carousel made with jquery for a website and it works just great.. except that i find that the page can take a while to load initially.. i thought that if i actually downloaded the pictures that i'm using for the background instead of loading them via ' http://www.whatever.jpg ', that the page might load faster.. but i'm kind of a noob still.. and haven't been able to figure out why this isn't working.. Here is my code: 我在用网站的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();
});
}());

i've searched around for a while now... thanks for the help! 我已经搜索了一段时间...感谢您的帮助!

You do yourself no favors trying to pre-load the images right before they are loaded for display in your CSS. 您不希望尝试在将图像加载到CSS中之前立即预加载图像。 In either case, the images have to be loaded first before you can see them, so there is going to be a delay regardless. 无论哪种情况,都必须先加载图像才能看到它们,因此无论如何都会有延迟。

If the only thing that you want to change is the src attribute of the img s to be a local folder, then I assume the only change to otherwise working code is the strings in your images array point to local files. 如果您唯一要更改的是将imgsrc属性更改为本地文件夹,那么我认为对其他有效代码的唯一更改是images数组中指向本地文件的字符串。

If that's the case, and if you want to resolve the location correctly without adding some sort of directory changes ( ../ , img/ or the like), then you will need those images to be in the same directory as the html file , not the file.js file. 如果是这种情况,并且您想在不添加某种目录更改( ../ img/之类)的情况下正确解析位置,则需要将这些图像与html文件放在同一目录 ,不是file.js文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM