逐字显示句子。只显示一个句子

时间:2018-03-15 21:06:08

标签: javascript jquery html animation

我有以下代码:



<body>
  <div id="website-1">
    <a href="">
      <img src="https://cdn.pixabay.com/photo/2015/06/19/17/58/sample-815141_960_720.jpg" style="position: absolute; top:50%; transform:translateY(-50%); left:50%; transform: translateX(-50%); width:50%">
    </a>
  <div class="arrow3 bounce">
    <a href="#video"><i class="fa fa-angle-down fa-5x" aria-hidden="true" style="color:#ED4C67;" ></i></a>
  </div>
</div>
&#13;
#website-1 {
  width: 100%;
  height: 100vh;
  background: white;
  position: relative;
}

.arrow3 {
  position: absolute;
  bottom: 20px;
  left: 50%;
  margin-left: -20px;
  width: 40px;
  height: 60px;
}
&#13;
&#13;
&#13;

它逐字显示div元素的句子。现在我想编辑这段代码,让它现在只显示一个句子。

所以它看起来像这样:

  1. 第一句话逐字显示。
  2. 1秒延迟。
  3. 隐藏第一句话。
  4. 第二句逐字逐句显示。

1 个答案:

答案 0 :(得分:2)

您只需要迭代所有P's并添加setTimeout即可显示它。您需要计算setTimeout的延迟如下所述。

在这个节目中,当前的P,隐藏其兄弟姐妹并开始动画它所拥有的spans

var delay = 0;
// Iterate over all the P's
P.each(function(){
  // You need an IIFE to pass correct 'this'
  (function(that){
    // Add a setTimeout to hide/show P's
    setTimeout(function(){
      // Show current P and hide all of its siblings
      $(that).show().siblings().hide();
      // This is what you already had
      $(that).find('span').each(function(I) {
          $(this).delay(200 * I).fadeIn(800);
      });
    }, delay);
  })(this);
  // Delay is past delay + time to fade in all the spans + 1 sec break
  delay = delay+($(this).find('span').length+1)*200+1000;
});

var P = $('.sentences > p');

P.hide().contents().each(function() {
    var Words;
    if (this.nodeType === 3) {
        Words = '<span> ' + this.data.split(/\s+/).join(' </span><span> ') + ' </span>';
        $(this).replaceWith(Words);
    } else if (this.nodeType === 1) {
        this.innerHTML = '<span> ' + this.innerHTML.split(/\s+/).join(' </span><span> ') + ' </span>';
    }
});

P.find('span').hide().each(function() {
    if( !$.trim(this.innerHTML) ) {
        $(this).remove();
    }
});

var delay = 0;
// Iterate over all the P's
P.each(function(){
  // You need an IIFE to pass correct 'this'
  (function(that){
    // Add a setTimeout to hide/show P's
    setTimeout(function(){
      // Show current P and hide all of its siblings
      $(that).show().siblings().hide();
      // This is what you already had
      $(that).find('span').each(function(I) {
          $(this).delay(200 * I).fadeIn(800);
      });
    }, delay);
  })(this);
  // Delay is past delay + time to fade in all the spans + 1 sec break
  delay = delay+($(this).find('span').length+1)*200+1000;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sentences">
  <p>This is only a simple paragraph #1</p>
  <p>This is only a simple paragraph #2</p>
  <p>This is only a simple paragraph #3</p>
  <p>This is only a simple paragraph #4</p>
  <p>This is only a simple paragraph #5</p>
</div>