javascript - 背景图像不随 setInterval 改变
问题描述
我尝试使用setInterval
. 只有图像只改变一次。我试图改变宽度值,它可以工作。
var hero = document.getElementById('hero')
console.log(hero)
var heroBg = hero.style.backgroundImage;
console.log(heroBg)
function change() {
console.log('this is showing in the console')
if (hero.style.background === 'url(./images/image2.jpg)') {
console.log('this is not showing in the console')
hero.style.background = 'url(./images/image1.jpg)'
console.log('testcondition1')
} else {
console.log('this is showing in the console')
hero.style.background = 'url(./images/image2.jpg)'
}
}
setInterval(change, 3000);
编辑:这有效
if(hero.style.backgroundImage == 'url("./images/image2.jpg")'){
console.log('test1')
hero.style.backgroundImage = 'url("./images/image1.jpg")'
console.log('testcondition1')
}else{
console.log('test2')
hero.style.backgroundImage='url("./images/image2.jpg")'
}
我试图在括号内使用双引号,这很有效。外面的双引号和里面的单引号没有。
解决方案
我会利用数据属性来存储英雄的状态并在状态之间切换。
您可以使用currentState
inside of的值change
来确定要做什么。
不要试图通过条件来运行样式信息,因为你会度过一段糟糕的时光。
const maxStates = 2
const hero = document.getElementById('hero')
function change() {
let currentState = parseInt(hero.dataset.state || 0, 10)
currentState = (currentState + 1) % maxStates
hero.dataset.state = currentState
}
setInterval(change, 2000); // Update every 2 seconds.
#hero {
width: 200px;
height: 287px;
background-color: rgba(0, 0, 0, 0);
background-repeat: no-repeat;
background-position: top left;
background-image: url('https://placekitten.com/200/287');
}
#hero[data-state="1"] {
background-image: url('https://placekitten.com/200/286');
}
<div id="hero"></div>
推荐阅读
- python - 如何修复python中的无限循环
- ios - 未调用 handleRemoteNowPlayingActivity
- php - 从 PHP 中的数组内部获取数据
- android - 如何修复嵌套在 ScrollView 中的 BoxInsetLayout 内的包装元素
- javascript - object.innerHTML 没有正确更新?
- java - 在使用 Swagger UI 发出的请求中添加授权
- r - unquote a list of functions inside R dplyr functions
- javascript - 如何解决快速拨号?
- c - 对变量声明感到困惑
- java - 如何在 textview 或 toast msg 中从服务器接收数据