最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How do I cycle through pictures in JavaScript? - Stack Overflow

programmeradmin1浏览0评论

My html:

<img src="C:\Users\Shady\Downloads\restaurant\food1.jpg" alt="rotating image" width="400" height="300" id="rotator">

My Javascript:

<script type="text/javascript">
        (function() {
            var rotator = document.getElementById('rotator');  
            var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';                          
            var delayInSeconds = 5;                            

            var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];

            var num = 0;
            var changeImage = function() {
                var len = images.length;
                rotator.src = imageDir + images[num++];
                if (num == len) {
                    num = 0;
                }
            };
            setInterval(changeImage, delayInSeconds * 1000);
        })();
        </script>

Everything makes sense to me but for some reason it is not working. It is only showing the first picture (doesn't cycle through the pictures). Please let me know if you need anything else. Thank you.

My html:

<img src="C:\Users\Shady\Downloads\restaurant\food1.jpg" alt="rotating image" width="400" height="300" id="rotator">

My Javascript:

<script type="text/javascript">
        (function() {
            var rotator = document.getElementById('rotator');  
            var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';                          
            var delayInSeconds = 5;                            

            var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];

            var num = 0;
            var changeImage = function() {
                var len = images.length;
                rotator.src = imageDir + images[num++];
                if (num == len) {
                    num = 0;
                }
            };
            setInterval(changeImage, delayInSeconds * 1000);
        })();
        </script>

Everything makes sense to me but for some reason it is not working. It is only showing the first picture (doesn't cycle through the pictures). Please let me know if you need anything else. Thank you.

Share Improve this question edited Apr 8, 2015 at 14:07 ShadyBears asked Apr 8, 2015 at 14:05 ShadyBearsShadyBears 4,19714 gold badges47 silver badges70 bronze badges 7
  • By rotate do you mean change images from a list (cycle through them) or actually rotate them, like change the orientation by x degrees? – Jon Surrell Commented Apr 8, 2015 at 14:08
  • Cycle.. I changed the title/description. – ShadyBears Commented Apr 8, 2015 at 14:09
  • 1 looks fine for me, check th rotator variable with console.log. maybe the JavaScript doesnt finds the div, becuase the DOM isnt ready – Nano Commented Apr 8, 2015 at 14:09
  • Where is the script placed? before or after the img tag? – Markai Commented Apr 8, 2015 at 14:10
  • I tried a test function by defining it as var testf = function() {... and then I used it in setInterval. It did not work. I changed it to function testf() {... and used it in setInterval. It worked. – kainaw Commented Apr 8, 2015 at 14:11
 |  Show 2 more ments

4 Answers 4

Reset to default 3

you are getting element 'rotator' before document is loaded so it doesn't exist.

Try this:

function start() {
    var rotator = document.getElementById('rotator');  
    var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';                          
    var delayInSeconds = 1;                            

    var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];

    var num = 0;
    var changeImage = function() {
        var len = images.length;
        rotator.src = imageDir + images[num++];
        if (num == len) {
            num = 0;
        }
    };
    setInterval(changeImage, delayInSeconds * 1000);
};
window.onload=function(){
start();
}

Preload the images:

<script type="text/javascript">

var slideimages = new Array() // create new array to preload images
slideimages[0] = new Image() // create new instance of image object
slideimages[0].src = "firstcar.gif" // set image src property to image path, preloading image in the process
slideimages[1] = new Image()
slideimages[1].src = "secondcar.gif"
slideimages[2] = new Image()
slideimages[2].src = "thirdcar.gif"

</script>

Display the first image:

<img src="firstcar.gif" id="slide" width="100" height="56" />

Create the slideshow(cycle):

<script type="text/javascript">

//variable that will increment through the images
var step=0

function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.getElementById('slide').src = slideimages[step].src
if (step<2)
step++
else
step=0
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}

slideit()

</script>

This is how you can try...it works fine for me....

<html>
<body>
<img src="file:///C:/Users/Public/Pictures/Sample%20Pictures/test1 (2).jpg" alt="rotating image" width="400" height="300" id="rotator"> 
<script type="text/javascript">
    (function() {
        var rotator = document.getElementById('rotator');  
        var imageDir = 'file:///C:/Users/Public/Pictures/Sample%20Pictures/';                         
        var delayInSeconds = 5;                            

        var images = ['test1.jpg', 'test1 (2).jpg', 'test1 (3).jpg', 'test1 (4).jpg', 'test1 (5).jpg', 'test1 (6).jpg', 'test1 (7).jpg', 'test1 (8).jpg'];

        var num = 0;
        var changeImage = function() {
            var len = images.length;
            rotator.src = imageDir + images[num++];
            if (num == len) {
                num = 0;
            }
        };
        setInterval(changeImage, delayInSeconds * 100);
    })();
    </script>   
</body> 
</html>

You try to access the DOM element with the id rotator before it got loaded. There are two ways to bypass this problem:

  1. You can move your script tag below the img tag, because then the javascript get's execute after the img element has been loaded:

    <img src="C:\Users\Shady\Downloads\restaurant\food1.jpg" alt="rotating image" width="400" height="300" id="rotator">
    <script type="text/javascript">
        (function() {
            var rotator = document.getElementById('rotator');  
            var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';                          
            var delayInSeconds = 5;                            
    
            var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
    
            var num = 0;
            var changeImage = function() {
                var len = images.length;
                rotator.src = imageDir + images[num++];
                if (num == len) {
                    num = 0;
                }
            };
            setInterval(changeImage, delayInSeconds * 1000);
        })();
    </script>
    
  2. You can set the onload event handler for the document to your anonymous function (or give it a name if you like):

    <script type="text/javascript">
    window.onload = function() {
        var rotator = document.getElementById('rotator');  
        var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';                          
        var delayInSeconds = 5;                            
    
        var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
    
        var num = 0;
        var changeImage = function() {
            var len = images.length;
            rotator.src = imageDir + images[num++];
            if (num == len) {
                num = 0;
            }
        };
        setInterval(changeImage, delayInSeconds * 1000);
    };
    </script>
    
发布评论

评论列表(0)

  1. 暂无评论