首页 > 解决方案 > 背景图像不随 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")'
    }

我试图在括号内使用双引号,这很有效。外面的双引号和里面的单引号没有。

标签: javascript

解决方案


我会利用数据属性来存储英雄的状态并在状态之间切换。

您可以使用currentStateinside 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>


推荐阅读