滑块fadein / fadeout

时间:2017-03-23 14:26:59

标签: javascript jquery

我为我的网站创建了此滑块,但我需要在fadeIn/out时应用next/prev。谁能解释我怎么做或给我看代码?

JS

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";
}

HTML

<div class="container">
  <img class="mySlides" src="http://placehold.it/600x200">
  <img class="mySlides" src="http://placehold.it/600x150" style="display:none">
  <img class="mySlides" src="http://placehold.it/600x100" style="display:none">
  <img class="mySlides" src="http://placehold.it/600x200" style="display:none">
    <button onclick="plusDivs(-1)">&#10094;</button>
    <button onclick="plusDivs(1)">&#10095;</button>
</div>

1 个答案:

答案 0 :(得分:0)

我认为你可以取代它:

for (i = 0; i < x.length; i++) {
  x[i].style.display = "none";   
}
x[slideIndex-1].style.display = "block";

有了这个:

$('.mySlides:visible').fadeOut(function() {
   $(x[slideIndex-1]).fadeIn();
});

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}
  $('.mySlides:visible').fadeOut(function() {
     $(x[slideIndex-1]).fadeIn();
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
      <img class="mySlides" src="http://placehold.it/600x200">
      <img class="mySlides" src="http://placehold.it/600x150" style="display:none">
      <img class="mySlides" src="http://placehold.it/600x100" style="display:none">
      <img class="mySlides" src="http://placehold.it/600x200" style="display:none">

      <button onclick="plusDivs(-1)">&#10094;</button>
      <button onclick="plusDivs(1)">&#10095;</button>
</div>