javascript - 当我的用户将鼠标悬停在元素上时,尝试计算秒数
问题描述
我是 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()};
解决方案
只需删除 mouseenter 函数中的“var”即可。如下更改
document.getElementById("ceva").onmouseenter = function(){
x = setInterval(incrementSeconds, 1000)
};
推荐阅读
- javascript - 在 javascript 中调用的 C# 函数,它在页面加载之前执行。为什么?
- python - 为什么从我的自定义分布中抽取的随机样本不遵循 pdf?
- .htaccess - 在 .htaccess 中重写 URL - PHP
- javascript - 在电子内部使用时,Howler 抛出“解码音频数据失败”
- gradle - 为 Web 应用程序自定义工作目录运行 gradle 运行任务/项目结构
- android - 如何通过Intent打开应用并清除后台堆栈返回应用
- python - 浮点对象不可迭代 [Python]
- javascript - 如何使用 CSS 更改标签中图像的高度和宽度?
- javascript - window.postMessage 到具有空源的 iframe
- javascript - 在 useCallback 没有更新状态值