创建淡出/中而不是显示无/阻止

时间:2016-10-21 13:14:12

标签: javascript jquery

我正在尝试使用JS淡入淡出幻灯片而不是显示无/块。这需要使用css完成还是我可以在JS中完成。感谢

代码:

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentDot(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
    console.log('SHOWSLIDES');
      var i;
      var slides = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("nav-dot");
      if (n > slides.length) {slideIndex = 1}
      if (n < 1) {slideIndex = slides.length}
      for (i = 0; i < slides.length; i++) {
          slides[i].style.display = "none";
      }
      for (i = 0; i < dots.length; i++) {
          dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex-1].style.display = "block";
      dots[slideIndex-1].className += " active";
}

还是更好地将其转换为jquery并使用.fadeOut()/ .fadeIn()

1 个答案:

答案 0 :(得分:1)

之前:看一下jQuery的源代码:

  1. .fadeIn()
  2. http://james.padolsey.com/jquery/#v=1.11.2&fn=fadeIn

    1. .animation()
    2. http://james.padolsey.com/jquery/#v=1.11.2&fn=animate

      这是一种如何做到这一点的方法:

      var fadeInBtn = document.getElementById('fadeIn');
      fadeInBtn.addEventListener('click', function() {
        var testString = document.getElementById('test');
        fadeIn(testString, 30);
      });
      
      var fadeOutBtn = document.getElementById('fadeOut');
      fadeOutBtn.addEventListener('click', function() {
        var testString = document.getElementById('test');
        fadeOut(testString, 60);
      });
      
      
      
      function fadeIn(element, speed) {
        var interval = setInterval(function () {
          
          var opacity = parseFloat(element.style.opacity);
          if(opacity >= 1.0) {
             clearInterval(interval);
          }
      
          element.style.opacity = opacity + 0.1;
        }, speed);
      };
      
      function fadeOut(element, speed) {
        var interval = setInterval(function () {
          
          var opacity = parseFloat(element.style.opacity);
          if(opacity <= 0) {
             clearInterval(interval);
          }
      
          element.style.opacity = opacity - 0.1;
        }, speed);
      }
      div {
        font-size: 300%;
      }
      <button id="fadeIn">Test .fadeIn()</button>
      <button id="fadeOut">Test .fadeOut()</button>
      <div id="test" style="opacity: 0">Example String</div>

      另一种解决方案是使用CSS(3)。我在这里引用了这个已经问过的问题:Using CSS for fade-in effect on page load