首页 > 解决方案 > 当我的用户将鼠标悬停在元素上时,尝试计算秒数

问题描述

我是 Javascript 的新手,当我的用户将鼠标悬停在元素上时,我正在尝试计算秒数。但我无法让间隔停止。到目前为止,这是我的代码。谢谢

 var seconds = 0;
var el = document.getElementById('ceva');

function incrementSeconds() {
seconds += 1;
el.innerText = "You have been here for " + seconds + " seconds.";

}

var x;

document.getElementById("ceva").onmouseenter = function() {var x = 
setInterval(incrementSeconds, 1000)};

function mouseLeave() {
clearInterval(x`);
}

 document.getElementById("ceva").onmouseleave = function() {mouseLeave()};

标签: javascriptsetinterval

解决方案


只需删除 mouseenter 函数中的“var”即可。如下更改

document.getElementById("ceva").onmouseenter = function(){
  x = setInterval(incrementSeconds, 1000)
};

推荐阅读