准备就绪时的随机背景

Random Background at the Ready

本文关键字:背景 随机 准备就绪      更新时间:2023-09-26

这真的很简单,但我不是程序员。我只是具有一般问题解决技能的暴力代码。这是行不通的。这个代码被设置为对背景图像进行随机化,并且它是有效的。但是,它被设置为等待页面完全加载,因此它的时间太不一致。据我所知,document.ready会给我更一致(更快)的时间安排,但我似乎无法让它发挥作用。这是工作版本:

<script type="text/javascript"> 
    function changeImg(imgNumber) { 
        var myImages = [
            "http://static.tumblr.com/0obftwk/u0Am8xfjf/streetarturbaninphilade.jpg",
            "http://static.tumblr.com/0obftwk/Xmym8xfet/artmuseumarea.jpg",
            "http://static.tumblr.com/0obftwk/znNm8xf9e/rowhouseswestphilly.jpg",
            "http://static.tumblr.com/0obftwk/af1m8xf87/phillyvista.jpg",
            "http://static.tumblr.com/0obftwk/ydIm8xf74/chinagatephiladelphia.jpg",
            "http://static.tumblr.com/0obftwk/8kCm8xf41/broadritner.jpg"
        ]; 
        var imgShown = document.body.style.backgroundImage; 
        var newImgNumber =Math.floor(Math.random()*myImages.length);
        document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')'; 
    }   
    window.onload=changeImg;
</script>

如果在加载页面之前知道图像列表,请在CSS中粘贴对图像的引用,然后只更改文档上的className。body

.bgClass1 {background-image: url(http://static.tumblr.com/0obftwk/u0Am8xfjf/streetarturbaninphilade.jpg)}

等等…

<body class="bgClass1">

否则,使用js 构建预加载程序