Image display based on time

久未见 提交于 2019-12-12 03:34:21

问题


I'm trying to create an image rotator that displays certain images at certain times, but also rotates at other times in the day.

When I first created it, I just had it rotate every three seconds. That worked fine. But once I added the code to make a different image show up at different times, it quit working all together. Part of the problem is I'm confused about where I should put the setInterval and clearInterval. Anyway, here;s the code.

     <img id="mainImage" src="/arts/rotatorpics/artzone.jpg" />

JS:

    var myImage = document.getElementById("mainImage");
    var imageArray = ["arts/rotatorpics/artzone.jpg",
         "arts/rotatorpics/bach.jpg",
         "arts/rotatorpics/burns.jpg"];
    var imageIndex = 0;
    var changeImage = function() {
        mainImage.setAttribute("src", imageArray[imageIndex]);
        imageIndex++;
        if (imageIndex >= imageArray.length) {
            imageIndex = 0;
        }

    }

    var newDay = new Date(); //create a new date object
    var dayNight = newDay.getHours(); //gets the time of day in hours

    function displayImages() {
        if (dayNight >= 10 && dayNight <= 12) {
            mainImage.setAttribute("src", imageArray[1]);
        } else if (dayNight >= 17 && dayNight <= 19) {
            mainImage.setAttribute("src", imageArray[2]);
        } else {
            var intervalHandle = setInterval(changeImage, 3000);
        }
        myImage.onclick = function() {
            clearInterval(intervalHandle);
        };
    }​

回答1:


first of all, all your variables seem to be are global, please dont do that, use an anonymous function-wrapper which executes your code (immediately (read about IIFE here. this is not part of your problem, but just good and clean coding style.

(function() {
  // your code here
})();

then i think one of your problems is your displayImages-function, which you declare but never call!

just should call it at the end of your code (or just leave it out)

displayImages();

if you want your images not to be swapped between 10-12 and 17-19 your code should then work as expected. if the images should swap even at this times, you shouldnt put the setInterval into the last else (inside your displayImages-function



来源:https://stackoverflow.com/questions/13780344/image-display-based-on-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!