需要添加淡入到图像幻灯片中

时间:2017-06-08 08:35:42

标签: javascript jquery html css animation

我需要在幻灯片放映的现有代码上添加淡入淡出和淡出我的图像的动画。用户单击按钮时,图像必须淡入/淡出。这是我的代码。

HTML:

<div id="imageSlider">

  <button id="prevBTN" onclick="prev()"> <b>Prev</b> </button>

  <button id="nextBTN" onclick="next()"> <b>Next</b> </button>
</div>

使用Javascript:

var images = [
  "HTMLcert.jpg",
  "CSScert.jpg",
  "javaScriptCert.jpg",
  "PHPcert.jpg"
];

var num = 0;

function next() {
  var slider =
    document.getElementById("slider");
  num++;
  if (num >= images.length) {
    num = 0;
  }
  slider.src = images[num];
}

function prev() {
  var slider =
    document.getElementById("slider");
  num--;
  if (num <= 0) {
    num = images.length - 1;
  }
  slider.src = images[num];
}

如何添加淡入和淡出现有的java脚本代码。

2 个答案:

答案 0 :(得分:1)

您可以使用CSS3 annimation,通过创建自定义动画,使用最后一个添加类,然后在单击按钮时切换类。

发表一个工作片段:

var images = [
  "http://ramg1.net/images/3.jpg",
  "https://www.gregbowe.com/assets/img/htmlcert.jpg",
  "http://www.lordlamer.de/wp-content/uploads/2011/02/php-cert.jpg",
  "http://www.michellekeselgiancola.com/images/certs/uploads/phpcert.jpg"
];

var num = 0;

function next() {
  var slider =
    document.getElementById("slider");
  num++;
  if (num >= images.length) {
    num = 0;
  }
  
  slider.classList.remove("fade");
  slider.src = images[num];
  setTimeout(function(){slider.classList.add("fade");},10);
  //slider.classList.add("fade");
}

function prev() {
  var slider =
    document.getElementById("slider");
  num--;
  if (num <= 0) {
    num = images.length - 1;
  }
  
  slider.classList.remove("fade");
  slider.src = images[num];
  setTimeout(function(){slider.classList.add("fade");},10);
  //slider.classList.add("fade");
}
/* create the fade custom annimation wich set 0 to 1 opacity on an element */
@-webkit-keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-moz-keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-o-keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}

/* create the class that trigger the annimation */
.fade {
  -webkit-animation: fade 2s ease; /* Safari 4+ */
  -moz-animation:    fade 2s ease; /* Fx 5+ */
  -o-animation:      fade 2s ease; /* Opera 12+ */
  animation:         fade 2s ease; /* IE 10+, Fx 29+ */
}
<div id="imageSlider">

  <img id="slider" class="fade" src="http://ramg1.net/images/3.jpg" width="400px" height="80%" />

  <button id="prevBTN" onclick="prev()"> <b>Prev</b> </button>

  <button id="nextBTN" onclick="next()"> <b>Next</b> </button>
</div>

答案 1 :(得分:1)

您可以在javascript函数中的活动滑块元素中添加和删除类,如下所示:

var slider = document.getElementById("slider");
slider.className += " active";
setTimeout(function(){
  slider.classList.remove("active");
}, 100);

然后你的CSS会看起来像这样:

.active {
   animation: fade 1s;
}

@keyframes fade {
  from { opacity: 0; }
  to { opacity: 1 }
}