0

我正在尝试将背景图像设置为固定并拉伸以适合屏幕。如果在每个页面加载时切换背景图像,我正在使用的 js

<script language="JavaScript">
<!-- Activate cloaking device
var randnum = Math.random();
var inum = 1;
// Change this number to the number of images you are using.
var rand1 = Math.round(randnum * (inum-1)) + 1;
images = new Array
images[1] =    "http://simplywallpaper.net/pictures/2010/10/22/how_to_train_your_dragon_monstrous-nightmare.jpg"
images[2] = "tiler3.jpg"
images[3] = "wicker3.jpg"
images[4] = "aaa4.jpg"
// Ensure you have an array item for every image you are using.
var image = images[rand1]
// Deactivate cloaking device -->
</script>

身体

<script language="JavaScript">
<!-- Activate cloaking device
document.write('<body background="' + image + '" text="white" >')
</script>

js 本身可以很好地随机化图像,但当前设置为 1 个图像

4

2 回答 2

0

inum需要设置为 1 以外的值。您可以将其设置为数组中的图像数。

此外,数组从索引 0 开始,因此为了更安全,您应该相应地索引您的数组。

<script language="JavaScript">

// setup your image array
var images = new Array;
images[0] = "firstImage.jpg";   
... 
images[4] = "lastImage.jpg";

// alternative image array setup
var images = [ 'firstImage.jpg', 'secondImage.jpg', ... ,'lastImage.jpg' ];

// check to see if the image list is empty (if it's getting built somewhere else)
if (images.length) {
  // set inum
  var inum = images.length;
  var randnum = Math.random();
  var randIndex = Math.floor(randnum * inum);


  // Ensure you have an array item for every image you are using.
  var imageFile;
  if (randIndex < images.length) {
    imageFile = images[randIndex];
  }
...

</script>

在身体里

<script type="text/javascript">
  window.onload = function() {
    if (imageFile) {
      var body = document.getElementsByTagName("body")[0];
      if (body) { body.setAttribute('style',"background:url('"+imageFile+"'); text: white;"); }
    } 
 }
</script>
于 2013-11-10T01:00:46.913 回答
0

很简单,将两个脚本更改为:

<script type="text/javascript">
var images = [ 'http://tinyurl.com/qhhyb8k'
             , 'http://tinyurl.com/nqw2t9b'
             , 'http://tinyurl.com/nkogvoq'
       //    , 'url 4'
             ]
,    image = images[ (Math.random() * images.length)|0 ]
; //end vars

window.onload=function(){
    document.body.style.background=
        "url('"+image+"') no-repeat center center fixed";
    document.body.style.backgroundSize=
        "cover";  // width% height% | cover | contain 
};
</script>

无需配置,只需添加/删除/更改 url。

示例小提琴在这里

希望这可以帮助。

于 2013-11-10T01:04:47.140 回答