Cannot set property 'src' of null

前端 未结 4 2020
一整个雨季
一整个雨季 2021-01-21 12:25

I am trying to rotate an image using javascript and I was trying some code I found on adobes website that does what I was looking for. When I run it it gives me the error: Unca

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 12:27

    Your script is loaded before the body of your page, so the rotator element is not found. Remove the var rotator = ... line and put it inside the changeImage function instead:

    (function () {
        var rotator;
        var rotatedImageId = 'rotator';           // change to match your HTML
        var imageDir = 'images/';
        var delayInSeconds = 5;
        // list image names
        var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg'];
    
        // don't change below this line
        var num = 0;
        var changeImage = function () {
            if (!rotator)
                rotator = document.getElementById(rotatedImageId);
            if (!rotator)
                return;
    
            var len = images.length;
            rotator.src = imageDir + images[num++];
            if (num == len) {
                num = 0;
            }
        };
        setInterval(changeImage, delayInSeconds * 1000);
    })();
    

提交回复
热议问题