Javascript 页面加载时显示随机图像而不使用 body 标签中的 onload
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2777479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display random image when page loads without utilizing onload in the body tag
提问by Peachy
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?
我正在尝试创建一段相当简单的 JavaScript,每次页面加载时,它都会显示一个数组中的随机图像。我需要找到一种方法来运行它,而无需向 body 标记添加代码。有没有办法做到这一点,比如说,在 body 标签中放置一个 onload 函数?
Here's what I have that relies on the onLoad:
这是我依赖于 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?
任何替代想法来实现这一目标?
回答by Robusto
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:
Wombleton 的回答是我会做的。但是,还有另一种方法可以做到。在正文标记中,无论您要放置该随机图像的何处,请放置一个脚本,该脚本使用图像的标记执行 document.write。确保您有一组图像 URL 并替换,如下所示:
<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>
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.
同样,这并不理想,但如果您不想使用任何类型的 onload 事件,而不仅仅是您放入<body>标签中的事件,则这很有用。
回答by wombleton
Adapted from jQuery's readyfunction, and making some assumptions about the image types:
改编自 jQuery 的ready函数,并对图像类型做了一些假设:
(function() {
var urls = ['1', '2', '3', '4'];
function swap() {
document.getElementById('theImage').setAttribute('src', urls[Math.round(Math.random() * urls.length)] + '.jpg');
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
window.addEventListener( 'load', swap, false );
// If IE event model is used
} else if ( document.attachEvent ) {
window.attachEvent( 'onload', swap );
}
})();
回答by Jorgesys
With a few changes this code will load images randomly and his respective link to load.
通过一些更改,此代码将随机加载图像并加载其各自的链接。
<html>
<head/>
<title>Jorgesys Html test</title>
<script type="text/javascript">
var imageUrls = [
"http://prueba.agenciareforma.com/appiphone/android/img/newspapers/stackoverflow.png"
, "http://ww.mydomain.com/img/newspapers/reforma.png"
, "http://ww.mydomain.com/img/newspapers/nytimes.png"
, "http://ww.mydomain.com/img/newspapers/oglobo.png"
, "http://ww.mydomain.com/img/newspapers/lefigaro.png"
, "http://ww.mydomain.com/img/newspapers/spiegel.png"
];
var imageLinks = [
"http://www.stackoverflow.com"
, "http://www.reforma.com"
, "http://www.nytimes.com/"
, "https://oglobo.globo.com/"
, "http://www.lefigaro.fr/international/"
, "http://www.spiegel.de/international/"
];
function getImageHtmlCode() {
var dataIndex = Math.floor(Math.random() * imageUrls.length);
var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';
img += imageUrls[dataIndex];
img += '\" alt=\"Jorgesys Stackoverflow.com\"/></a>';
return img;
}
</script>
</head>
<body bgcolor="white">
<script type="text/javascript">
document.write(getImageHtmlCode());
</script>
</body>
</html>
回答by user2671076
Your answer can be found at glados.cc/myfaucet.
there is a script for download there which has the code you are looking for
here is a brief synopsis:
create file config.php and put this inside:
您可以在 glados.cc/myfaucet 上找到答案。
那里有一个可供下载的脚本,其中包含您正在寻找的代码,这是一个简短的概要:创建文件 config.php 并将其放入:
<?php
// Advertisement Codes
// All ads rotate. There are 3 types: square, text, and banner. Add HTML code to the array
$squareAds = array('<iframe scrolling="no" style="border: 0; width: 250px; height: 250px;" src="http://myadserver.com"></iframe>');
$textAds = array('<p><strong><a href="http://yoururl.com">YourURL</a></strong></p>', '<p><strong>Get your own site</strong> <a href="http://yoursite.com">here</a></p>');
$bannerAds = array('<iframe scrolling="no" style="border: 0; width: 468px; height: 60px;" src="http://youradserver.com"></iframe>
');
?>
Then, on the page you are serving, say, index.php to display your random links or images or text simply put:
然后,在您正在服务的页面上,例如 index.php 显示您的随机链接或图像或文本,只需简单地输入:
<?php
require_once('config.php');
function getAd($arr){
return $arr[rand(0, count($arr)-1)];
}
echo "any plain text or html" . getAd($textAds) . "any plain text or html" . getAd($bannerAds) . "any plain text or html" . getAd($squareAds) . "any plain text or html";
?>
Of course, you can create as many $xxxAds arrays and name them whatever you want, and you can fill in the arrays with whatever html or jscript to be displayed, as well as an unlimited number per array, in csv format you can also create as many new "getAd" functions with different names so that you can have multiple unique iframe ads being displayed on one page
当然,您可以创建任意多个 $xxxAds 数组并随意命名它们,并且您可以使用要显示的任何 html 或 jscript 填充数组,以及每个数组的无限数量,在 csv 格式中您也可以创建许多具有不同名称的新“getAd”函数,以便您可以在一个页面上显示多个唯一的 iframe 广告
回答by Kishan Chauhan
Add image in array with full path or directory path, after refresh page image add in body tag like <body background="images/image1.jpg">
使用完整路径或目录路径在数组中添加图像,刷新页面图像后添加正文标签,如 <body background="images/image1.jpg">
<script type="text/javascript">
function changeRandomimage() {
var imageArray = ["images/image1.jpg","images/image2.jpg","images/image3.jpg"];
var randomImage = Math.floor(Math.random() * imageArray.length);
document.body.background = imageArray[randomImage];
}
changeRandomimage();
</script>
回答by Anthony
You could place this in javascript at the bottom of the page, with a timeout.
您可以将其放置在页面底部的 javascript 中,并带有超时。
setTimeout(swapImage, 500); or somesuch.
setTimeout(swapImage, 500); 或诸如此类。
回答by Senica Gonzalez
Just don't put you javascript inside a function.
只是不要把你的 javascript 放在一个函数中。
if you take it out of the function it will run when the page loads.
如果您将其从函数中取出,它将在页面加载时运行。
When it's in the function, it won't run unless called.
当它在函数中时,除非被调用,否则它不会运行。
回答by Tgr
You could just use document.write to generate the img tag. Or even something like <img src="javascript:Math.round(Math.random()*3)+'.jpg';" />
您可以使用 document.write 来生成 img 标签。或者甚至像<img src="javascript:Math.round(Math.random()*3)+'.jpg';" />
回答by kennebec
you don't need an onload in the body tag- add a handler in the script, in the head, or in another script that loads before the body .
您不需要在 body 标记中加载 onload - 在脚本、头部或在 body 之前加载的另一个脚本中添加处理程序。
(function(){
var fun=function(){
// definefunction
}
if(window.addEventListener){
window.addEventListener('load', fun,false);
else if(window.attachEvent)window.attachEvent('load', fun);
})();

