javascript imageslider setinterval

时间:2015-11-10 00:42:28

标签: javascript setinterval

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);

2 个答案:

答案 0 :(得分:1)

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

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>

答案 1 :(得分:-1)

解决此问题(在加号附近添加单引号)

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