onclick随机div背景图片

时间:2019-10-01 13:38:05

标签: javascript css

我不知道如何通过单击div背景之一来将具有相同背景图像的4个div更改为另一个随机图像。在我的脚本中,只有一张图片会更改。

我尝试使用文档getElementByClassName并将ID更改为class,但这根本不起作用。 我尝试了多个ID,例如box1-random1,box2-random2,并在js中添加了它,但两者都不起作用...

<div class="wrapper" id="my-button">
  <div class="box1" id="random"></div>
  <div class="box2" ></div>
  <div class="box3" ></div>
  <div class="box4" ></div>
</div>


.box1 {
  background-position: 0% 100%;
}
.box3 {
  background-position: 0% 100%;
}
.box2 {
  background-position: 100% 0%;
}
.box4 {
  background-position: 100% 0%;
}
.box1, .box2, .box3, .box4 {
  background-size: cover;
  background-repeat: no-repeat;
  background-image: url("http://lorempixel.com/800/800/cats/6");
}


var myData = {
    1: {
        imageUrl:"http://lorempixel.com/800/800/cats/4",
        text: "This is the text for image 1"
    }, 
    2: {
        imageUrl: "http://lorempixel.com/800/800/cats/4",
        text: "This is the text for image 2"
    }, 
    3: {
        imageUrl: "http://lorempixel.com/800/800/cats/4",
        text: "This is the text for image 3"
    }, 
    4: {
        imageUrl: "http://lorempixel.com/800/800/cats/4",
        text: "This is the text for image 4"
    }, 
    5: {
        imageUrl: "http://lorempixel.com/800/800/cats/5",
        text: "This is the text for image 5"
    }, 
    6: {
        imageUrl: "http://lorempixel.com/800/800/cats/6",
        text: "This is the text for image 6"
    }, 
    7: {
        imageUrl: "http://lorempixel.com/800/800/cats/7",
        text: "This is the text for image 7"
    }, 
    8: {
        imageUrl: "http://lorempixel.com/800/800/cats/8",
        text: "This is the text for image 8"
    }, 
    9: {
        imageUrl: "http://lorempixel.com/800/800/cats/9",
        text: "This is the text for image 9"
    }, 
    10: {
        imageUrl: "http://lorempixel.com/800/800/cats/10",
        text: "This is the text for image 10"
    }
};
function changeImage(){
    var randomNumber = Math.floor((Math.random() * 10) + 1);
    document.getElementById("random").style.background = "url('"+myData[randomNumber].imageUrl+"')";
    document.getElementById("text").innerHTML = myData[randomNumber].text;    
}
document.getElementById("my-button").addEventListener("click",changeImage);

`

1 个答案:

答案 0 :(得分:0)

像这样更改您的功能:

function changeImage(){
    var divs = document.querySelectorAll(".wrapper > div");
    var randomNumber = Math.floor((Math.random() * 10) + 1);
    for(var i=0; i<divs.length; i++){
        divs[i].style.background = "url('"+myData[randomNumber].imageUrl+"')";
        divs[i].innerHTML = myData[randomNumber].text;    
    } 
}