I want to write a javascript function to change background image after every 24 hours for 30 days.
For example, I have 4 images, image1.jpg, image2.jpg, image3.jpg and image4.jpg.
I want image1.jpg to be displayed on Monday. Then by midnight I want to swap automatically to image2.jpg and so on.
I was thing to use a java script function like this
function changeImg() {
var now = new Date(),
hours=now.getHours(),
minutes=now.getMinutes(),
seconds=now.getSeconds(),
开发者_StackOverflow中文版 dayD=now.getDate(),
dayM=now.getMonth()+1,
datY=now.getFullYear(),
timer = setTimeout("changeImg()",200);
}
var imgArray = new imgArr[xyz.png,abc.png,........,30.png]
Now my question is that how to change automatically image after 24hours. If I use a for loop to increment the counter to change the image will it work. And is it correct way to do this and if i am using this way Is the timer will maintain the previous counter value.
I want that every day at 9:00 am the background image will change.
This should be a server side task. However if you must use JavaScript then...
Put this in the section of your page or as an external script file.
<script>
function render_image() {
var images = [
'00001.jpg',
'00002.jpg',
'00003.jpg',
'00004.jpg',
'00005.jpg',
'00006.jpg',
]
// define the start date (alter this)
var first = new Date("2011-09-03");
// which image
var src = images[
// count days since start (int)
(((new Date().getTime() - first.getTime())
/ 86400 / 1000) | 0)
% images.length
];
// create image element
var im = document.createElement('img');
im.src = src;
// return code
var di = document.createElement('div');
di.appendChild(im);
return di.innerHTML;
}
</script>
Put this in the html page at the location you want the image to appear.
<script> document.write(render_image()); </script>
I'd suggest setting a timeout for no more than every minute. In the timeout, check the date, and if has changed, then get the image from the list, and then write the new url to the appropriate place in the document. At the end of the timeout, always start the next timeout. No for loop would be necessary.
精彩评论