所以这是一件事。我希望数字每秒递增1,而鼠标指针位于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>
答案 0 :(得分:2)
您每秒都会添加相同的事件侦听器。我认为这不是你想要的
当鼠标不在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>
答案 1 :(得分:2)
你可以试试这个:
var num = -1, count;
$('div').hover(startCounter, stopCounter);
function startCounter(){
$("#myID").html( ++num );
count = setTimeout(startCounter, 1000);
}
function stopCounter() {
clearInterval(count);
}
&#13;
<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>
&#13;
答案 2 :(得分:0)
设置鼠标悬停间隔并清除mouseout上的间隔。确保声明间隔,以便您可以停止它。
var count = 0;
$('body').on('mouseover', 'div', function () {
inc = setInterval(function () {
count++;
$('#myID').text(count);
}, 1000);
}).on('mouseout', 'div', function () {
clearInterval(inc);
});