用inner.HTML添加淡入效果

时间:2018-09-03 03:51:33

标签: javascript jquery css innerhtml

在使用inner.HTML时希望淡入内容。

当前代码;

<td style="width: 20%;" class="responsive-td" valign="top">
          <div id="placeholder1" class="placeholder1" style="color:white;"></div>
        </td>

if (//logic here){

          document.getElementById('placeholder1').innerHTML ='add this with fading effect';

          setTimeout(addFn1, 300);
           function addFn1() {
            document.getElementById('placeholder2').innerHTML ='add this with fading effect';}       

    setTimeout(addFn2, 1200);
           function addFn2() {
            document.getElementById('placeholder3').innerHTML ='add this with fading effect';}
         } 

我尝试使用css,但是由于setTimeout而无法创建效果。

是否有使用CSS或JS的简单解决方案?甚至还有jQuery(如果需要)?

2 个答案:

答案 0 :(得分:0)

使用jQuery很容易,因为有这样的简单动画方法。

看看.fadeIn().fadeOut()

if (true){

  $('#placeholder1').html('add this with fading effect').fadeIn(600);

  setTimeout(addFn1, 300);
  function addFn1() {
    $('#placeholder2').html('add this with fading effect').fadeIn(600);}       

  setTimeout(addFn2, 1200);
  function addFn2() {
    $('#placeholder3').html('add this with fading effect').fadeIn(600);}
}
body{
  background-color:black;
}
.placeholder1{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td style="width: 20%;" class="responsive-td" valign="top">
  <div id="placeholder1" class="placeholder1" style="color:white;"></div>
  <div id="placeholder2" class="placeholder1" style="color:white;"></div>
  <div id="placeholder3" class="placeholder1" style="color:white;"></div>
</td>

答案 1 :(得分:0)

也许您可以在更改文本时尝试将不透明度设置为old =零到new = one。

选项:使用CSS3和Js(无jquery)

document.addEventListener('DOMContentLoaded', function() {
  var quotes = ["Hello", "there", "everyone"];
  var infos = document.querySelectorAll('div.info');
  var repeat = Array.prototype.slice;
  var fadeIn = function(i) {
    if (!infos[i]) {
      return;
    }
    infos[i].innerHTML = quotes[i];
    infos[i].classList.add("open");
  };
  repeat.call(infos).forEach(function(el) {
    var callBack = function(e) {
      var that = this;
      repeat.call(infos).forEach(function(cur, ind) {
        if (cur == that) {
          fadeIn(1 + ind);
          return false;
        }
      });
    };
    el.addEventListener('webkitAnimationEnd', callBack);
    el.addEventListener('animationEnd', callBack);
  });
  fadeIn(0); /* trigger fade */
});
.info {
  opacity: 0;
  filter: alpha(0%);
  border: 1px solid #ccc;
  margin: 1px 2px;
}

@keyframes fade {
  from {
    opacity: 0;
    filter: alpha(0%);
  }
  to {
    opacity: 1;
    filter: alpha(100%);
  }
}

.info.open {
  -webkit-animation: fade .3s;
  -moz-animation: fade .3s;
  -ms-animation: fade .3s;
  -o-animation: fade .3s;
  animation: fade .3s;
  opacity: 1;
  filter: alpha(100%);
}
<div class="info"></div>
<div class="info"></div>
<div class="info"></div>