鼠标悬停时文本动画,鼠标悬停时停止和重置

时间:2016-08-21 17:36:03

标签: javascript jquery html animation

我希望有一些静态的文本,但是当用户将鼠标悬停在文本上时,它会通过不同单词的数组进行动画处理,当用户移除鼠标时停止并显示静态单词。

在其他SO帖子的帮助下我走得很远:

changing text periodically in a span from an array with jquery

但是不能让循环队列停止并在移除悬停后返回到原始单词。

我想要一个句子,例如:

<p>Here is a sentence <span id="rotate">this</span> is what changes</p>

因此,如果用户将鼠标悬停在&#34;这个&#34;上,则通过淡入/淡出其他单词数组来动画,例如:

var terms = ["newword1", "newword2", "newword3"];

但是当移除悬停时,它会停止动画队列并重置以显示&#34;这个&#34;试。

这是我到目前为止所做的:

var terms = ["term 1", "term 2", "term 3"];

function rotateTerm() {
  var ct = $("#rotate").data("term") || 0;
  $("#rotate").data("term", ct == terms.length -1 ? 0 : ct + 1).text(terms[ct]).fadeIn()
  .delay(2000).fadeOut(200, rotateTerm);
};

主要来自其他SO帖子,但已将触发器更改为:

$("#rotate").mouseenter(function(){
  $(rotateTerm);
});

$("#rotate").mouseleave(function(){
});

所以现在这会发生鼠标悬停,这很棒,但是我很难放入什么东西,以及#34; mouseleave&#34;用于停止当前正在运行的旋转文本。

1 个答案:

答案 0 :(得分:2)

我认为你正在寻找这样的东西:

var terms = ["term 1", "term 2", "term 3"],
  interval;

function displayNext() {
  var ct = $("#rotate").data("term") || 0;
  $("#rotate").fadeOut(200);
  setTimeout(function() {
    $("#rotate").data("term", ct == terms.length - 1 ? 0 : ct + 1).text(terms[ct]).fadeIn();
  }, 190);
};

function rotateTerm() {
  displayNext();
  interval = setInterval(function() {
    displayNext();
  }, 2000);
}

$("#rotate").mouseenter(function() {
  rotateTerm();
});

$("#rotate").mouseleave(function() {
  clearInterval(interval);
  setTimeout(function() {
    $('#rotate').text('this');
  }, 200);
});

工作小提琴:here

相关问题