通过单击按钮,随机出现两张图片,每张图片应包含在两个框中,共12张。但是出了点问题。需要建议来解决此问题。
var startBtn = document.getElementById("start-button");
var imgBox1 = document.getElementById("firstBox");
var imgBox2 = document.getElementById("secondBox");
var images = [
'/assets/img/pic1.png',
'/assets/img/pic2.png',
'/assets/img/pic3.png',
'/assets/img/pic4.png',
'/assets/img/pic5.png',
'/assets/img/pic6.png',
'/assets/img/pic7.png',
'/assets/img/pic8.png',
'/assets/img/pic9.png',
'/assets/img/pic10.png',
'/assets/img/pic11.png',
'/assets/img/pic12.png',
];
function loadImages(imgArr){
for(var i=0; i< imgArr.length; i++) {
console.log(imgArr[i]);
var img = new Image();
img.src = imgArr[i];
document.getElementById('output').appendChild(img);
}
}
startBtn.onclick = function(){
imgBox1.style.backgroundImage = images[Math.floor(Math.random()*images.length)];
imgBox2.style.backgroundImage = images[Math.floor(Math.random()*images.length)];
}
答案 0 :(得分:0)
设置背景图片时,您需要使用CSS的url
函数:
startBtn.addEventListener("click", function() {
imgBox1.style.backgroundImage = `url('${images[Math.floor(Math.random() * images.length)]}')`
imgBox2.style.backgroundImage = `url('${images[Math.floor(Math.random() * images.length)]}')`
});
答案 1 :(得分:0)
您没有添加要单击其ID为start-button
的按钮。本质上,您什么也没点击。
<button type="button" id="start-button" style="">Start</button>