鼠标停止后的触发代码
Trigger code after mouse has stopped
我有一个在鼠标输入时触发的代码块。我还有一个代码块,可以检测鼠标何时停止移动。
我希望mouseenter代码只在鼠标在输入的对象内停止移动时运行。
// Add events to each dot
for (var i = 0; i < dots.length; i++) {
dots[i].addEventListener('mouseenter', function (event) {
var target = event.target;
// Add a class called moving when follow dot is in a transition
followDot.classList.add('moving');
targetsPosition[0] = target.style.left;
targetsPosition[1] = target.style.top;
// Detect if the dot is moving left or right
if (followDot.style.left < targetsPosition[0]) {
removeMovingClasses();
followDot.classList.add('moving-right');
} else if (followDot.style.left > targetsPosition[0]) {
removeMovingClasses();
followDot.classList.add('moving-left');
}
//
followDot.style.left = targetsPosition[0];
});
}
超时代码:
// Detect when the mouse has stopped
document.onmousemove = function(){
clearTimeout(timeout);
timeout = setTimeout(function () {
// console.log('mouse stopped');
}, 300);
}
试试这个解决方案,当鼠标在div for example
上闲置特定时间时,可以触发事件。
HTML:
<h2>fire event when mouse is idle</h2>
<div id="sample">
</div>
CSS:
#sample {
width:200px;
height:200px;
background: #aaa;
}
JavaScript:
idleTimer = null;
idleState = false;
idleWait = 2000;
(function ($) {
$(document).ready(function () {
var $sample = $("#sample");
$('*').bind('mousemove keydown scroll', function () {
clearTimeout(idleTimer);
if (idleState == true) {
// Reactivated event
if($sample.is(":hover")) {
alert('mouse has moved again');
}
}
idleState = false;
idleTimer = setTimeout(function () {
// Idle Event
if($sample.is(":hover")) {
alert('mouse has stopped for two seconds');
}
idleState = true; }, idleWait);
});
$("body").trigger("mousemove");
});
}) (jQuery)
您可以将idleWait
变量更改为所需的周期(本例中为2秒)
jsfiddle示例
我希望它对你有效:)
一切看起来都很好,您只需要做一个小的更改。尝试将mousemove事件添加到您的目标区域,而不是文档(除非它是整个文档)。此外,您应该将您的第一个块包装在一个函数中,以便在鼠标停止时调用。
示例
function mouseHasStopped(){
//code in first block...
}
//adding an event listener to whatever element is entered . in this example i'm using "element" as our entered object ...
element.addEventListener("mousemove",function(){
clearTimeout(timeout);
timeout=setTimeout(mouseHasStopped,300);
});
希望这能帮助
相关文章:
- 鼠标事件,我的代码出了什么问题
- 鼠标停止后的触发代码
- 使用 JS 代码设置鼠标位置,并将位置放在其他 JS 代码中
- 如何将鼠标悬停在链接上时显示demo_test.txt的内容?我哪里出错了,我的代码应该是什么样子
- 如何将鼠标离开添加到我的文件中?以及我的代码会是什么样子
- 如何更改此代码,使其仅在没有鼠标移动时才重定向
- 在 C# 代码隐藏中添加鼠标悬停属性
- 使用合成鼠标事件驱动 Javascript 代码
- 谷歌地图API:显示代码中的鼠标悬停窗口
- 我的鼠标向上代码有什么问题
- 在jquery就绪调用函数中应用鼠标悬停代码
- 尝试实现鼠标移动到这个基本的javascript代码
- 代码在Codepen中工作,而不是在浏览器中工作:JavaScript在鼠标滚轮上缩放SVG
- 在下面的代码中,在Fabric.js中单击鼠标时,Canvas层消失,Firefox在创建画布到图像时停止响应
- 我将如何获取此.scrollTop代码并对其进行修改以在鼠标悬停或滚动时暂停其功能
- 为什么当我用鼠标粘贴文本时,我的文本框单词计数代码不能工作?
- 我的javascript鼠标滚轮动画代码有什么问题?
- 在angularjs中鼠标离开和鼠标取出的代码是什么?没有jquery
- 如何检测click()是鼠标单击还是由某些代码触发
- 如何获得确切的鼠标向下的坐标?为什么我的代码不工作