【问题标题】:How do I switch between images indefinitely in JavaScript如何在 JavaScript 中无限期地在图像之间切换
【发布时间】:2020-11-19 02:22:21
【问题描述】:

(我正在使用香草 JS) 所以我希望图像每 1 秒切换一次。但是它只切换一次并停止。

HTML

<img class="pic" id="pic" src=
"images/lightsOff.png">

JavaScript

function imageChange() {
  document.getElementById("pic").src = 
"images/lightsOn.png";
}

setInterval(imageChange, 1000)

【问题讨论】:

  • 它不会“停止”——你只是永远不会告诉它恢复到原来的样子

标签: javascript html function time


【解决方案1】:

您的代码只是一遍又一遍地设置相同的 src。您需要检查 src 是什么并进行调整。我只会使用数据属性并在两者之间以间隔翻转。无需跟踪布尔值或检查图像是什么。

var img = document.querySelector("#flip");
window.setInterval(function () {
  var newSrc = img.dataset.src;
  img.dataset.src = img.src;
  img.src = newSrc;
}, 2000);
&lt;img data-src="http://placekitten.com/g/200/200" src="http://placekitten.com/200/200" id="flip"/&gt;

如果你想在没有任何 JavaScript 的情况下做到这一点,你有 CSS

.alterImg {
  width: 200px;
  height: 200px;
  animation: swapimg 5s infinite alternate;
}

@keyframes swapimg {
  0% {
    background-image: url('http://placekitten.com/200/200')
  }
  30% {
    background-image: url('http://placekitten.com/200/200')
  }
  70% {
    background-image: url('http://placekitten.com/g/200/200')
  }
  100% {
    background-image: url('http://placekitten.com/g/200/200')
  }
}
&lt;div class="alterImg"&gt;&lt;/div&gt;

【讨论】:

    【解决方案2】:

    你好,你应该试试这个:

    let toggle = false;
    function imageChange() {
      document.getElementById("pic").src = toggle ? "images/lightsOn.png" : "images/lightsOff.png";
      toggle=!toggle;
    }
    setInterval(imageChange, 1000)
    

    您的问题是您每秒将图像设置为lightsOff,但我们实际上需要每秒在lightsOfflightsOn 之间切换图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多