我想在悬停时随机化字符以获取特定ID。 它在鼠标输入时工作正常但在鼠标离开时无法停止并返回初始文本。
这是代码。
jQuery(function($) {
function text_shuffle() {
"use strict";
var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var $_inter = setInterval(function() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}, 100);
}
$("#text-shuffle").mouseenter(text_shuffle);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>
感谢您的帮助
答案 0 :(得分:1)
你需要在mouseleave上清除你的间隔。你没有调用mouseleave函数,因此你的代码会无限期地扰乱你div中的字符。
我所做的只是将间隔设置为变量并在mouseleave上清除变量。
jQuery(function($) {
all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var int;
var counter = 0;
function textShuffle() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}
$("#text-shuffle").hover(function() {
int = setInterval(textShuffle, 100);
}, function () {
clearInterval(int);
document.getElementById("text-shuffle").innerText = "Home";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>
答案 1 :(得分:1)
使用clearInterval
停止随机化字符,当鼠标离开文本时替换原始文本。
jQuery(function($) {
function text_shuffle() {
"use strict";
var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$_inter = setInterval(function() {
var text = document.getElementById("text-shuffle");
text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
counter = (counter+1)%text.innerHTML.length;
}, 100);
}
var value, $_inter;
$("#text-shuffle").mouseenter( function(){
value = $(this).html();
text_shuffle();
}).
mouseout(function(){
clearInterval($_inter);
$(this).html(value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text-shuffle">Home</div>
答案 2 :(得分:1)
(function(){
'use strict';
var all = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
elem = document.getElementById("text-shuffle"),
orig = elem.innerHTML;
var $_inter;
function text_shuffle()
{
var counter = 0;
$_inter = setInterval( function()
{
elem.innerHTML = elem.innerHTML.substring(0, counter) + all.charAt(( Math.random() * all.length ) | 0 ) + elem.innerHTML.substring(counter + 1);
counter = (counter+1) % elem.innerHTML.length;
}, 100);
}
function clear() { clearInterval( $_inter ); elem.innerHTML = orig };
$("#text-shuffle").hover( text_shuffle, clear )
}())