背景图像不会随着setInterval改变

时间:2020-07-21 17:41:40

标签: javascript

我尝试使用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")'
    }

我尝试在括号内使用双引号,并且可以正常工作。外面的双引号和里面的单引号都没有。

3 个答案:

答案 0 :(得分:0)

您可能希望使用布尔值标志,而不是比较可能在浏览器之间不一致的背景CSS属性。

let flag = true;
function change() {
  console.log('this is showing in the console')
  if (flag) {
    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)'
  }
  flag = !flag;
}

答案 1 :(得分:0)

我会利用数据属性存储英雄的状态,然后在状态之间进行切换。

您可以使用currentState中的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>

答案 2 :(得分:-1)

如果将背景更改为 backgroundImage

hero.style.background