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

簡単です。両方のスクリプトを次のように変更します。

<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 に答える
0

inum1 以外に設定する必要があります。配列内の画像の数に設定できます。

また、配列はインデックス 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 に答える