在鼠标悬停上的文字动画,停止并在鼠标悬停时重置
问题描述:
我正在寻找一些静态的文本,但是当用户将鼠标悬停在文本上时,它会通过不同单词的数组进行动画制作,用户删除他们的鼠标。在鼠标悬停上的文字动画,停止并在鼠标悬停时重置
我得到这个其他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>
因此,如果用户将鼠标悬停在“此”,那么它动画由衰落/出去的换句话说,例如数组:
var terms = ["newword1", "newword2", "newword3"];
但是当悬停被移除时,它将停止动画队列并重置以再次显示“this”。
这是我到目前为止有:
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(){
});
所以现在这个触发鼠标悬停,这是伟大的,但是我无法在“mouseleave”函数中放置现在正在运行的旋转文本。
答
我认为你在寻找这样的事情:
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
这看起来相当不错,但如果你把鼠标移动到改变文本的中心,并且不要完全移动鼠标指针,有时文本会随机“闪烁”或一次在两个或三个状态之间跳转。任何想法是什么造成这个? – Richard
@Richard你是对的,这是因为有时'fadeOut()'和'fadeIn()'之间触发'mouseleave'事件,所以我改变了超时时间来解决这个问题。 – Hulothe
@Richard您可能希望将鼠标悬停在段落本身(块元素)上,而不是跨度(内联元素)。 https://jsfiddle.net/NotInUse/6tgz1gsa/3/ +1虽然。 – Scott