每次页面刷新时更改div的背景图像

时间:2015-07-07 19:31:16

标签: javascript jquery html css

根据我在互联网上看到的内容,我应该能够在每次使用此javascript脚本刷新页面时更改div的背景图像。它由于某种原因不起作用。任何帮助将不胜感激。

这是html

<div class="home-intro show-for-medium-up" id="home-intro">
</div>

这是css

.home-intro{
  background-image: url("../images/1.png");
  background-color:grey;
  height:500px;
  color:$white;
  text-align:center;
  }

这是js

<script>


function randomImage(){
  var images = [
   '../images/1.png',
   '../images/2.png',
   '../images/3.png'];
  var size = images.length;
  var x = Math.floor(size * Math.random());
  console.log(x);
  var element = document.getElementsByClassName('home-intro');
  console.log(element);
  element[0].style["background-image"] = "url("+ images[x] + ") no-repeat;";
}

document.addEventListener("DOMContentLoaded", randomImage);

3 个答案:

答案 0 :(得分:3)

唯一的问题是您正在尝试设置background-image属性的no-repeat属性。 no-repeat background属性的一个属性。

http://codepen.io/kevinfargason/pen/EjEeMa

答案 1 :(得分:0)

我会做的

{-# LANGUAGE FlexibleContexts #-}


class StringLike a where
 getString :: a->String

class (StringLike Smells) =>IntLike a where
 getInt :: a-> Int


instance StringLike Colors where
 getString x = "Hello"


data Colors = Blue | Red
data Smells = Rose | Trash

并使用

<body onload="randomImage()">`

var x=Math.floor(size * Math.random());

编辑:

或jQuery

document.getElementById("home-intro").style.backgroundImage = "../images/" + x + ".png";

答案 2 :(得分:0)

您需要在样式中添加高度。

function randomImage(){
   var images = ["./hanuman.png","./jesus.jpg","./hanuman.png"];
   var size = images.length;
   var x = Math.floor(size * Math.random());
   console.log(x);
   document.getElementById("homeintro").style.height="1000px";
  document.getElementById("homeintro").style.backgroundImage = 
  "url("+images[x] +")";
                }