停止逐行JavaScript动画循环播放

时间:2018-09-11 12:08:11

标签: javascript

我目前正在使用一段JavaScript,它会在一行文本中逐渐消失。

JavaScript不是强力的,我正在努力阻止动画循环播放。

任何有关如何实现此目标的帮助和建议都将非常有用。 这是小提琴https://jsfiddle.net/spittman/7wpqkfhj/5

的链接

谢谢!

JavaScript

$(document).ready(function() {


function fadeInLine(line){
  $('<span />', {
    html: line.trim(),
    style: "opacity: 0"
  })
  .appendTo($greeting)
  .animate({opacity:1}, 500);
}

function rotateLines(interval){
  setTimeout(() => {
    if(i >= lines.length-1){
      i = 0;
      interval = 1500;
      setTimeout(()=>{ $greeting.empty(); }, interval)
    } else {
      fadeInLine(lines[i]);
      i++;
      interval = 1500;
    }
    rotateLines(interval);
  }, interval);
}

const $greeting = $('div#container p');
const text = $greeting.html();
const lines = text.split("\n").filter((e) => e.replace(/\s+/, ""));
let i = 0;

$greeting.empty();
rotateLines();



});

HTML

<div id="container">
  <p>
    There’s another side to London.<br>
    Beyond the jurisdiction of The City.<br>
    Undiscovered by outsiders.<br>
    Loved by insiders.<br>
    An ever-changing place...<br>
    That teases our wildside and thrills our artside.<br>
    Blurs our workside into our playside.<br>
    Where we live on the brightside.<br>
    And explore our darkside.<br>
    Hidden in plain sight, this is Bankside.<br>
    London’s other side.<br>
    .
  </p>
</div>

2 个答案:

答案 0 :(得分:1)

将排定的呼叫放在else子句中,然后删除greeting.empty()行。

function rotateLines(interval){
  setTimeout(() => {
    if(i >= lines.length-1){
      i = 0;
      interval = 1500;
      // setTimeout(()=>{ $greeting.empty(); }, interval)
    } else {
      fadeInLine(lines[i]);
      i++;
      interval = 1500;
      rotateLines(interval);
    }
    // rotateLines(interval); 
  }, interval);
}

JSFiddle

整个文本淡入淡出后,动画将停止。

答案 1 :(得分:0)

只需摆脱设置元素和计数器的if子句。

function rotateLines(interval){
  setTimeout(() => {
      fadeInLine(lines[i]);
      i++;
      interval = 1500;

    rotateLines(interval);
  }, interval);
}

JSFiddle