jquery无法更改background-image属性

时间:2017-07-07 12:53:24

标签: javascript jquery css background-image

就像标题所说,由于某种原因,我的函数不想对background-image属性进行更改。我还让函数更改background-color以检查它是否正常工作。所以似乎问题不在语法中。

function feedSlide () {
  var x = [
    '../img/feed1.png', 
    '../img/feed2.png', 
    '../img/feed3.png',
    '../img/feed4.png'
  ];
  var y = ['green', 'red', 'blue', 'yellow'];
  for (var i = 0; i < x.length; i++) {
    setTimeout(function(z) { return function() { 
      console.log(x[z]); 
      $('#feedback').css({"background-image" : "url(" + x[z] + ")"});
      $('#feedback').css({"background-color" : y[z] });
    }; }(i), 1000*i);
  }
}
#feedback {
  width: 400px;
  text-align: justify;
  padding: 10px;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aboutDiv">
  <div id="feedback"></div>
  <div id="audio"></div>
</div>

我现在已经好几个小时了,一切似乎都变了,但background-image。任何信息都非常受欢迎。

2 个答案:

答案 0 :(得分:0)

每次解决此问题的尝试都失败后,我在CSS动画中找到了解决方案。

 #feedback {
  height: 110px;
  width: 380px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  animation-name: feedSlide;
  animation-duration: 40s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
 }  

@keyframes feedSlide {
 0.00% {background-image: url(../img/feed1.png); opacity: 0;}
 3% {opacity: 1;}
 22% {opacity: 1;}
 25% {background-image: url(../img/feed1.png); opacity: 0;}
 26% {background-image: url(../img/feed2.png); opacity: 0;}
 29% {opacity: 1;}
 47% {opacity: 1;}
 50% {background-image: url(../img/feed2.png); opacity: 0;}
 51% {background-image: url(../img/feed3.png); opacity: 0;}
 54% {opacity: 1;}
 72% {opacity: 1;}
 75% {background-image: url(../img/feed3.png); opacity: 0;}
 76% {background-image: url(../img/feed4.png); opacity: 0;}
 79% {opacity: 1;}
 97% {opacity: 1;}
 100% {background-image: url(../img/feed4.png); opacity: 0;}
}

答案 1 :(得分:0)

您可以尝试以下代码,

function feedSlide () {
  var x = [
    'feed1.png', 
    'feed2.png', 
    'feed3.png',
    'feed4.png'
  ];
  var y = ['green', 'red', 'blue', 'yellow'];
  for (var i = 0; i < x.length; i++) {
    setTimeout(function(z) { return function() { 
      console.log(x[z]); 
      var element = document.getElementById('#feedback');
      element.style.backgroundImage = "url('img/" + x[z] + "')";
      element.style.backgroundColor = y[z];
    }; }(i), 1000*i);
  }
}