这个javascript滑块出了什么问题?

时间:2017-04-20 10:44:52

标签: javascript html css

这是我第一次尝试使用javascript 此图像滑块不起作用,我不知道出了什么问题 这就是我试图做的事情 https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_self



var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
  showDivs(slideIndex += n);
}
function showDivs (n) {
  var i;
  var x = document.getElementByClassName("mySlides");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length;}
  for (i = 0 ,i < x.length ,i++) {
    x[i].style.display = "none";
  }
  x[slideIndex-1].style.display = "block";
}
&#13;
.container {
  width:980px;
  position: relative;
}
.container img {
  width: 100%;
}
button {
  position: absolute;
  color: black;
  background: white;
  width: 50px;
  height: 50px;
}
.left {
  top:50%;
  left: :0;  
}
.right {
  top:50%;
  right: 0;
}
&#13;
<div class="container">
  <img class="mySlides" src= "images/img_fjords.jpg">
  <img class="mySlides" src="images/img_forest.jpg">
  <img class="mySlides" src="images/img_lights.jpg">
  <button class="left" onclick = "plusDivs(-1)">&#10094;</button>
  <button class="right" onclick = "plusDivs(+1)">&#10095;</button>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您需要将for更改为

for (i = 0; i < x.length; i++) {

而不是:

for (i = 0, i < x.length, i++) {

(使用;代替,)。

并将getElementByClassName更改为getElementsByClassName(注意元素末尾的s)。

var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
  showDivs(slideIndex += n);
}
function showDivs (n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length;}
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex-1].style.display = "block";
}
.container {
  width:980px;
  position: relative;
}
.container img {
  width: 100%;
}
button {
  position: absolute;
  color: black;
  background: white;
  width: 50px;
  height: 50px;
}
.left {
  top:50%;
  left: :0;  
}
.right {
  top:50%;
  right: 0;
}
<div class="container">
  <img class="mySlides" src= "http://placehold.it/500">
  <img class="mySlides" src="http://placehold.it/501">
  <img class="mySlides" src="http://placehold.it/502">
  <button class="left" onclick = "plusDivs(-1)">&#10094;</button>
  <button class="right" onclick = "plusDivs(+1)">&#10095;</button>
</div>