开发者

Image changing every day of the year (365 days)

I need a little help with my code there are 366 images to change called 001.jpg, 002.jpg ... 366.jp开发者_JS百科g. It gets the date and put the picture for it. The code works but I can't get it to output in my img tag.

<html>
<head>
<script type="text/javascript">

var firstJan = Math.floor((new Date().setFullYear(new Date().getFullYear(),0,1))/86400000);
var today = Math.ceil((new Date().getTime())/86400000);
var dayOfYear = today-firstJan;

var bgdImage;
if((dayOfYear+'').length == 1)
bgdImage = '00'+dayOfYear+'.jpg';
else if((dayOfYear+'').length == 2)
bgdImage = '0'+dayOfYear+'.jpg';
else
bgdImage = dayOfYear+'.jpg';

document.getElementById('bla').src = "bgdImage";
</script>

</head>
<body onload=img()>

<img id="bla" width="100%" height="100%" />

</body>
</html>


Take the double-quotes off:

document.getElementById('bla').src = bgdImage;


Like I said in the initial comment, put the code in the function ìmg() you call in the <body onload="javascript:img();">. I also removed the quotes from your output statement to the src. document.getElementById('bla').src = bgdImage; bgdImage is your variable and putting it in quotes "bgdImage" is just a String with the text bgdImage inside.

<html>
<head>
<script type="text/javascript">

function img()
{
var firstJan = Math.floor((new Date().setFullYear(new Date().getFullYear(),0,1))/86400000);
var today = Math.ceil((new Date().getTime())/86400000);
var dayOfYear = today-firstJan;

var bgdImage;
if((dayOfYear+'').length == 1)
bgdImage = '00'+dayOfYear+'.jpg';
else if((dayOfYear+'').length == 2)
bgdImage = '0'+dayOfYear+'.jpg';
else
bgdImage = dayOfYear+'.jpg';

document.getElementById('bla').src = bgdImage;
}
</script>

</head>
<body onload="javascript:img();">

<img id="bla" width="100%" height="100%" />

</body>
</html>


One problem in your code looks like you are setting the src of the image to the String "bgdImage" rather than the variable. Try replacing the line with this:

document.getElementById('bla').src = bgdImage;

UPDATE

It also looks like you are trying to run the code before the img tag is set up. Try moving the script to after the img tag, or setting a timeout to execute it after the page has completely rendered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜