JavaScript 图像滑块设置间隔

javascript imageslider setinterval

本文关键字:设置 图像 JavaScript      更新时间:2023-09-26
var imagecount = 1;
var total = 3;

想知道为什么我不能以这种方式制作imageslider。我保存了图片,例如studentbild1studentbild2studentbild3。我如何让这些在这样的setinterval中显示出来。

window.setInterval(function slideA() {
    var image = document.getElementById('studentbild');
    imagecount = imagecount + 1;
    if(imagecount > total){ imagecount = 1;}
    if(imagecount < 1){ imagecount = total;}
    image.style.backgroundImage = 'url("studentbild" + imagecount + ".jpg")';
},1000);

删除内部双引号,用单引号替换它们:

image.style.backgroundImage = 'url("studentbild' + imagecount + '.jpg")';

url("studentbild1.jpg")

等。

var imagecount = 0;
var total = 3;
window.setInterval(function slideA() {
  var image = document.getElementById('studentbild');
  imagecount = imagecount + 1;
  if (imagecount > total) {
    imagecount = 1;
  }
  if (imagecount < 1) {
    imagecount = total;
  }
  image.style.backgroundImage = 'url("http://placehold.it/' + imagecount + '00")';
}, 1000);
#studentbild {
  width: 300px;
  height: 300px;
}
<div id="studentbild"></div>

修复此问题(在加号附近添加单引号(

image.style.backgroundImage = 'url("studentbild' + imagecount + '.jpg")';