创建一个在鼠标悬停时更改图片的事件

时间:2013-12-06 08:25:34

标签: javascript

我正在尝试创建一个更改鼠标上图片的事件。

var myImage = document.getElementById("mainImage");

var imageArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg",
                  "_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
var imageIndex = 0;

mainImage.mousover = function changeImage() {
    myImage.setAttribute("src",imageArray[imageIndex]);
    imageIndex++;
    if (imageIndex >= imageArray.length) {
        imageIndex = 0;
    }
}

// setInterval is also in milliseconds

mainImage.mousover = function () {
    var intervalHandle = setInterval(changeImage,1000);
}

myImage.onclick =  function() {
    clearInterval(intervalHandle);
};

mainImage是HTML中的对象,changeImage函数会更改当前图片。

我应该如何更改代码才能使其正常工作?

2 个答案:

答案 0 :(得分:1)

删除了在中间只显示“mainImage.mouseover =”的行

var myImage = document.getElementById("mainImage");

var imageArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg",
              "_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
var imageIndex = 0;



function changeImage() {
    myImage.setAttribute("src",imageArray[imageIndex]);
    imageIndex++;
    if (imageIndex >= imageArray.length) {
        imageIndex = 0;
    }
}

// setInterval is also in milliseconds

mainImage.onmousover = function () {

    var intervalHandle = setInterval(changeImage,1000);

}

myImage.onclick =  function() {
    clearInterval(intervalHandle);
};

答案 1 :(得分:0)

您遇到类似错误:

  1. mainImage.mousover =是语法错误。
  2. mainImage.mousover更改为mainImage.onmouseover
  3. 此外,您应该将您的代码包装在window.load事件处理程序中,因为它会在图像加载后强制浏览器执行您的代码。

    将代码更改为以下内容:

     window.onload = function () {
            var myImage = document.getElementById("mainImage");
    
    
            var imageArray = ["_images/overlook.jpg", "_images/winery_sign.jpg", "_images/lunch.jpg",
                              "_images/bigSur.jpg", "_images/flag_photo.jpg", "_images/mission_look.jpg"];
            var imageIndex = 0;
    
            //mainImage.mousover =
    
            function changeImage() {
                myImage.setAttribute("src", imageArray[imageIndex]);
                imageIndex++;
                if (imageIndex >= imageArray.length) {
                    imageIndex = 0;
                }
            }
    
            // setInterval is also in milliseconds
    
            var intervalHandle;
    
            mainImage.onmouseover = function () {
    
                intervalHandle = MyImageInterval();
    
            }
    
            document.getElementById("stopButton").onclick = function () {
                clearInterval(intervalHandle);
            };
    
            function MyImageInterval() {
                return setInterval(changeImage, 1000);
            }
        }
    

    注意:您应该使用类型=“按钮”添加输入,其中Id =“stopButton”。