【发布时间】:2010-06-27 01:08:20
【问题描述】:
我正在尝试使用 javascript 加载不在当前页面上的图像(来自图像链接数组),如果它们足够大,请将它们添加到数组中。我在当前页面加载后执行此操作,通过小书签或萤火虫控制台。使用FF。
我最接近的是下面,但这似乎不起作用,我猜这是因为尺寸测试在图像加载之前运行。显然我试图用'onload'解决这个问题是行不通的。我该如何解决这个问题,或者是否有更好/更简单的方法来完成这项任务?
(function() {
//create array for the images
var imageArray = new Array();
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
//dispImage = '<img src=' + x.src + '><br>';
//document.write('<center>' + dispImage + '</center>');
}
return true;
}
//given an array of imageLinks:
for (x in imageLinks){
//create an image form link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = loadIfBig(im);
}
//view results:
for (x in imageArray){
disp_image = '<img src='+imageArray[x].src+'><br>';
document.write('<center>'+disp_image+'</center>');
}
})();
更新:
谢谢!确定你是对的,我在这里遗漏了一些愚蠢的东西,但我做了你建议的改变,然后将元素写入 loadIfBig,但它似乎没有执行该函数。下面的当前代码,包括几个示例输入链接:
(function() {
var imageArray = new Array();
var imageLinks = ['http://1.bp.blogspot.com/_mfMRTBDpgkM/SwCwu1RPphI/AAAAAAAAJpw/v9YInFBW84I/s1600/800px-San_Francisco_in_ruin_edit2.jpg','http://2.bp.blogspot.com/_mfMRTBDpgkM/SwCwulSZ_yI/AAAAAAAAJpo/NsRcJdpz4Dk/s1600/San_Francisco_PC_59.jpg']
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
dispImage = '<img src=' + x.src + '><br>';
document.write('<center>' + dispImage + '</center>');
}
return true;
}
processImages = function(){
for (x in imageLinks) {
//create an image from link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = function(){
loadIfBig(this);
}
}
}
})();
【问题讨论】:
标签: javascript image loading