【问题标题】:Increment number every second as long as the mouse is on div只要鼠标在 div 上,每秒递增一次
【发布时间】:2015-04-09 12:51:15
【问题描述】:
所以这是一件事。当鼠标指针位于 div 元素上时,我希望数字每秒增加一,但不知何故它没有,我不知道问题出在哪里。
JS:
var num = 1;
var count = setInterval(
function(){
$("div").mouseover(
function(){
document.getElementById("myID").innerHTML = num;
num++;
}
);
}
,1000);
HTML:
<p id="myID"></p>
<div style="height:100px;width:100px;background-color:#3A5795;"></div>
【问题讨论】:
标签:
javascript
jquery
mouseover
increment
【解决方案1】:
您每秒都在添加相同的事件侦听器。我不认为那是你想要的。
当鼠标不在 div 上时,您还必须 clearInterval。
var num = 1;
$("div").mouseover(
function(){
incInterval= setInterval(function(){
document.getElementById("myID").innerHTML = num;
num++;
},1000);
}
);
$("div").mouseout(
function(){
clearInterval(incInterval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:100px;width:100px;background-color:#3A5795;"></div>
<p id="myID"></p>
【解决方案2】:
你可以试试这个:
var num = -1, count;
$('div').hover(startCounter, stopCounter);
function startCounter(){
$("#myID").html( ++num );
count = setTimeout(startCounter, 1000);
}
function stopCounter() {
clearInterval(count);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="myID">Hover the box to start counting.</p>
<div style="height:100px;width:100px;background-color:#3A5795;"></div>
【解决方案3】:
设置鼠标悬停间隔并清除鼠标悬停间隔。请务必声明时间间隔,以便您可以停止它。
var count = 0;
$('body').on('mouseover', 'div', function () {
inc = setInterval(function () {
count++;
$('#myID').text(count);
}, 1000);
}).on('mouseout', 'div', function () {
clearInterval(inc);
});