使用javascript随机化图像

时间:2014-03-06 11:18:03

标签: javascript

好的,这就是我想在这里做的事情: 我只是想在dv id splash下随机化图像,我将图像放在根文件夹中。我尝试使用函数randomImg()随机化代码,但输出为空。 有什么想法吗?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>HTML</title>
    <meta name="author" content="blahblahblah" />
    <!-- Date: 2014-03-06 -->
    <script type="text/javascript">
      function randomImg()
      {
        var images = new Array();
        images[0] = "img06.jpg";
        images[1] = "img07.jpg";
        images[4] = "img08.jpg";
        images[5] = "img09.jpg";
        images[6] = "img10.jpg";
        var random = Math.ceil(Math.random()* images.length);
        if (random == 0) {  random =1;  }
        document.write('<img src="images[random]">');
      }
    </script>
  </head>
<body>

<div id="header">
  <div id="logo">
  <h1><a href="#">Welcome</a></h1>
  <h2>Flower of the day</h2> 
  </div>
  <div id="splash"><img src="virus.jpg" alt="random images"/></div>
  <script type="text/javascript"> 
    document.getElementById('splash').firstElementChild.src = 'img09.jpg';
    randomImg();
  </script>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

更新此html:

 <div id="splash"><img id='image' src="virus.jpg" alt="random images"/></div>

而不是document.write('<img src="images[random]">'); put

document.getElementById('image').src=images[random];

否则

只需将document.write('<img src="images[random]">');替换为

即可
document.getElementById('splash').firstElementChild.src =images[random];