Javascript 随机背景标题刷新
我正在为自己建立一个网站。 我制作了一个标题背景,每次刷新时都会更改图像。 但有时标题中没有图像 有人能帮忙吗 Javascript:Javascript 随机背景标题刷新,javascript,html,arrays,Javascript,Html,Arrays,我正在为自己建立一个网站。 我制作了一个标题背景,每次刷新时都会更改图像。 但有时标题中没有图像 有人能帮忙吗 Javascript: addEventListener("load",init,false); function init(event){ var header = document.getElementById('mainheader'); var pictures = new Array(3); pictures[0]="pictures/test1.
addEventListener("load",init,false);
function init(event){
var header = document.getElementById('mainheader');
var pictures = new Array(3);
pictures[0]="pictures/test1.jpg";
pictures[1]="pictures/test2.gif";
pictures[2]="pictures/test3.jpg";
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.round((Math.random() * numPics));
header.style.background = 'url(' + pictures[chosenPic] + ')';
}
}
HTML:
您的问题是随机发生器代码。尝试:
var chosenPic = Math.floor(Math.random() * pictures.length);
生成的数字将从0变为3,3超出了数组边界。您需要使用小于数组长度的1,或者使用floor而不是round
var chosenPic = Math.round((Math.random() * (numPics-1)));
JS有时会返回3作为随机数。试试这个:
addEventListener("load",init,false);
function init(event){
var header = document.getElementById('mainheader');
var pictures = new Array(3);
pictures[0]="pictures/test1.jpg";
pictures[1]="pictures/test2.gif";
pictures[2]="pictures/test3.jpg";
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.round((Math.random() * numPics));
(chosenPic >= 3) ? 2 : chosenPic;
header.style.background = 'url(' + pictures[chosenPic] + ')';
alert(chosenPic);
}
}
最简单的解决方案:
Math.floor(Math.random() * numPics);
供参考:
Math.floor(Math.random() * numPics);