且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

页面加载时显示随机图像,而不使用body标签中的onload

更新时间:2023-11-10 21:49:58

Wombleton的回答就是我要做的。但是,还有另一种方法可以做到这一点。在正文标记中,无论您要将随机图像放在哪里,都可以使用带有图像标记的document.write脚本。确保您有一系列图片网址和替代品,如下所示:

Wombleton's answer is what I would do. However, there is another way to do it. In the body markup, wherever you are going to put that random image, put a script that does a document.write with the markup for the image. Make sure you have an array of image URLs and substitute, like so:

<html>
<head>
<title>Test</title>
<script type="text/javascript">
  var imageURLs = [
       "http://www.myserver.com/images/image1.png"
     , "http://www.myserver.com/images/image2.png"
     , "http://www.myserver.com/images/image3.png"
  ];
  function getImageTag() {
    var img = '<img src=\"';
    var randomIndex = Math.floor(Math.random() * imageURLs.length);
    img += imageURLs[randomIndex];
    img += '\" alt=\"Some alt text\"/>';
    return img;
  }
</script>
</head>
<body>
<script type="text/javascript">
  document.write(getImageTag());
</script>
</body>
</html>

同样,这并不理想,但如果你不想使用任何一种onload事件,而不仅仅是您放入< body> 标记的事件。

Again, this is not ideal, but is useful if you don't want to use any kind of onload event, not just the one you put in the <body> tag.