用于串行img加载的Javascript代码

时间:2011-01-12 14:12:40

标签: javascript

我是javascript的新手。我想要一个javascript代码,我可以加载一个以每天/每月/每年命名的图像。连载 我有以下代码:

var year = new Array();
year = ["08", "09", "10", "11"];

var month = new Array();
month = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JULY", "AUG", "SEP", "OCT", "NOV", "DEC"];

var date = new Array();
date = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];

var ims = "";
for (var x in year) {
 for (var y in month) {
  for (var z in date) {
   ims += "<im src=screencover/img/" + date[z] + "" + month[y] + "20" + year[0] + ".png>";
  }
 }
}
document.write(ims);

2 个答案:

答案 0 :(得分:0)

编辑:现在我明白了:)

尝试一下这个:

function nrpad(number, length) {
  var str = '' + number;
  while (str.length < length) {
      str = '0' + str;
  }
  return str;
}
var end_date = new Date(2011, 12, 1).getTime();
var start_date = new Date(2008, 1, 1).getTime();

var step = 86400000; // 1 day in msec
for(var ts = start_date; ts <= end_date; ts += step){
  var d = new Date(ts);
  var img = new Image();
  img.src = 'screencover/img/' + nrpad(d.getDay(),2) + nrpad(d.getMonth(),2) + nrpad(d.getFullYear(),2) + '.png';
  //console.log(img.src);
}

但如果您使用该示例,则必须将文件重命名为“DDMMYYYY.png”(使用数字月份)。

答案 1 :(得分:0)

使用内置的Date对象:

function getFullYearArray(year) {
    var dates = [new Date(year, 0, 1, 0, 0, 0)],
        oneday = 1000 * 60 * 60 * 24;
    for (var i = 0; i < 364; i++) {
        dates.push( new Date(dates[i].getTime() + oneday) );
    }
    // leap years, if last day is december 30, add one
    if ( dates[i].getDate() == 30 ) {
        dates.push( new Date(dates[i].getTime() + oneday) );
    }
    return dates;
}

// usage
y08 = getFullYearArray(2008);
for (var i = 0, l = y08.length, date; i < l; i++) {
    date = y08[i];
    console.log( date.toDateString() );
}

您必须解析值的日期字符串以构建您的图像src字符串,但这应该让您开始。

修改

我继续并构建了字符串:

function getFullYearArray(year) {
    var dates = [new Date(year, 0, 1, 0, 0, 0)],
        oneday = 1000 * 60 * 60 * 24;
    for (var i = 0; i < 364; i++) {
        dates.push( new Date(dates[i].getTime() + oneday) );
    }
    // leap years, if last day is december 30, add one
    if ( dates[i].getDate() == 30 ) {
        dates.push( new Date(dates[i].getTime() + oneday) );
    }
    return dates;
}

// usage
var ims = "",
    y08 = getFullYearArray(2008);
for (var i = 0, l = y08.length, date, m, d, y; i < l; i++) {
    date = y08[i].toDateString();
    d = date.substring(8, 10);
    m = date.substring(4, 7).toUpperCase();
    y = date.substring(11, 15);

    ims += "<img src=\"screencover/img/" + d + m + y + ".png\">\n";
}

console.log(ims);