页面加载时显示随机图像,而不使用body标签中的onload [英] Display random image when page loads without utilizing onload in the body tag

查看:86
本文介绍了页面加载时显示随机图像,而不使用body标签中的onload的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个相当简单的JavaScript,每次加载页面时都会显示一个数组中的随机图像。我需要弄清楚如何在不向body标签添加代码的情况下运行此方法。有没有一种方法可以实现这一点,例如,没有放置在body标签中的onload函数?

I'm trying to create a fairly simple piece of JavaScript that displays a random image from an array each time the page loads. I need to figure out a way to get this running without adding code to the body tag. Is there a way to accomplish this without, say, an onload function placed in the body tag?

这是我依赖于onLoad的东西:

Here's what I have that relies on the onLoad:

    ImageSwitch=new Array();
    ImageSwitch[0]='1.jpg';
    ImageSwitch[1]='2.jpg';
    ImageSwitch[2]='3.jpg';
    ImageSwitch[3]='4.jpg';

    function swapImage() 
    {
        document.getElementById("theImage").setAttribute("src", ImageSwitch[

Math.round(Math.random()*3)])
    }

完成此任务的任何其他想法?

Any alternative ideas to accomplish this?

推荐答案

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.

这篇关于页面加载时显示随机图像,而不使用body标签中的onload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆