0

关于 new Image() 的问题

我认为以下代码来自'JavaScript by Example Second Edition'

planet[0] = "images/Venus.jpg" 

错了,应该是

planet[0].src = "images/Venus.jpg" 

并更换

document.images["planet_pic"].src = planet[i]; 

document.images["planet_pic"].src = planet[i].src;

这样对吗?

<!DOCTYPE html>
<html>
<head>
    <title>Slide Show</title>
    <script type="text/javascript">
        var i = 0;
        var timeout;
        function preLoadImages() {
            if (document.images) {
                planet = new Array(); // global variable
                planet[0] = new Image();
                planet[0] = "images/Venus.jpg";
                planet[1] = new Image();
                planet[1] = "images/Neptune.jpg";
                planet[2] = new Image();
                planet[2] = "images/Earth.jpg";
                planet[3] = new Image();
                planet[3] = "images/Mars.jpg";
                planet[4] = new Image();
                planet[4] = "images/Jupiter.jpg";
            }
            else {
                alert("There are no images to preload");
            }
        }
        function startSlideShow() {
            if (i < planet.length) {
                document.images["planet_pic"].src = planet[i];
                i++;
            }
            else {
                i = 0;
                document.images["planet_pic"].src = planet[i];
            }
            timeout = setTimeout('startSlideShow()', 1500);
        }
        function stopSlideShow() {
            clearTimeout(timeout);
        }
    </script>
</head>
<body bgcolor="black" onload="preLoadImages()">
    <img name="planet_pic" src="/images/Jupiter.jpg" height="348"
        width="545px" />
    <form>
        <br />
        <br />
        <input type="button" value="Start Show"
            onclick="return startSlideShow();" />
        <input type="button" value="Stop Show"
            onclick="return stopSlideShow();" />
    </form>
</body>
</html>
4

2 回答 2

1

是的,应该是,

planet[0] = new Image();
planet[0].src = "images/Venus.jpg";
于 2012-09-20T08:53:41.957 回答
1

试试这个:

var list = ["Venus.jpg", "Neptune.jpg", "Earth.jpg", "Mars.jpg", "Jupiter.jpg"];
var img;
planet = []; // **WHY a global?** global variable

for (var i = 0; i < list.length; i++) {
  img = new Image();
  img.src = "images/" + list[i];
  planet[i] = img;
  // or planet.push(img);
}
于 2012-09-20T08:54:22.360 回答