每 10 秒使用 querySelector 更改背景图像不起作用
Change background image with querySelector every 10 sec not working
我尝试每 10 秒将 div 中的背景图像更改为随机图像 (img/1-10.jpg)。
背景只改变一次,而不是每 10 秒改变一次,因为它应该改变
...我每 10 秒收到一次警报(所以 setInterval 确实有效)。
function update() {
window.setInterval(function() {
alert('ok');
document.querySelector("#ri-grid div:nth-child(1)")
.style
.backgroundImage = "url(img/<?php echo rand(1,10);?>.jpg)";
}, 10000);
}
update();
.grid--layout-1 .grid__item:nth-child(1) {
background-image: url(img/1.jpg);
transition: background 5s linear;
}
<div class="grid grid--layout-1 grid--current" id="ri-grid">
<div class="grid__item 0"></div>
<div class="grid__item 1"></div>
<div class="grid__item 2"></div>
<div class="grid__item 3"></div>
</div>
使用JS生成随机数
<script type="text/javascript">
function update() {
window.setInterval(function() {
var index = Math.floor(Math.random() * 10) + 1; // Generates random number from 1 to 10
document.querySelector("#ri-grid div:nth-child(1)").style.backgroundImage = "url(img/" + index + ".jpg)";
}, 10000);
}
update();
</script>
使用这个:
Math.floor(Math.random() * 10) + 1
而不是 PHP 代码:
<?php echo rand(1,10);?>
我尝试每 10 秒将 div 中的背景图像更改为随机图像 (img/1-10.jpg)。
背景只改变一次,而不是每 10 秒改变一次,因为它应该改变 ...我每 10 秒收到一次警报(所以 setInterval 确实有效)。
function update() {
window.setInterval(function() {
alert('ok');
document.querySelector("#ri-grid div:nth-child(1)")
.style
.backgroundImage = "url(img/<?php echo rand(1,10);?>.jpg)";
}, 10000);
}
update();
.grid--layout-1 .grid__item:nth-child(1) {
background-image: url(img/1.jpg);
transition: background 5s linear;
}
<div class="grid grid--layout-1 grid--current" id="ri-grid">
<div class="grid__item 0"></div>
<div class="grid__item 1"></div>
<div class="grid__item 2"></div>
<div class="grid__item 3"></div>
</div>
使用JS生成随机数
<script type="text/javascript">
function update() {
window.setInterval(function() {
var index = Math.floor(Math.random() * 10) + 1; // Generates random number from 1 to 10
document.querySelector("#ri-grid div:nth-child(1)").style.backgroundImage = "url(img/" + index + ".jpg)";
}, 10000);
}
update();
</script>
使用这个:
Math.floor(Math.random() * 10) + 1
而不是 PHP 代码:
<?php echo rand(1,10);?>