我正在尝试设置一个随机交替的背景,该背景会在整个站点上定期更改。例如,在任何给定点,随机背景图像在一段时间内在每个页面上都是相同的。
目前我的背景图片每 30 分钟用这个 javascript 改变一次:(来自这里: http: //www.blogfodder.co.uk/post/2008/01/JavaScript-CSS-Random-Background-Image.aspx)
然而,问题是每个链接都会随机化每个新页面上的背景。
function ChangeCSSBgImg() {
if (!document.getElementById) return false;
var MyElement = "bgimg"
var ImgPath = "../i/"
if (!document.getElementById(MyElement)) return false;
var random_images = new Array ();
random_images[0] = "bg1.jpg"; // these are the background images
random_images[1] = "bg2.jpg";
random_images[2] = "bg3.jpg";
random_images[3] = "bg4.jpg";
random_images[4] = "bg5.jpg";
var $header = document.getElementById(MyElement);
var $backgroundurl = $header.style.backgroundImage;
var ImgURL = "url(" + ImgPath + random_images[rand(random_images.length)] + ")";
if ($backgroundurl != ImgURL) {
$header.style.backgroundImage = ImgURL;
}
movement = setTimeout("ChangeCSSBgImg()",108000000);
}
/* random number generator */
function rand(n) {
return ( Math.floor ( Math.random ( ) * n ) );
}
/* Custom onload function */
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
/* trigger onload */
addLoadEvent(ChangeCSSBgImg);