Sen*_*sso 6 javascript css jquery
我想要实现的目标:当我的鼠标移动时,然后执行此操作,但是当它停止移动大约半秒时,然后执行此操作,但当它再次开始移动时,然后执行此操作。这是我的临时 jQuery:
$(document).ready(function() {
$('.test').mouseenter(function(){
$(this).mousemove(function(){
$(this).css({
'background-color' : '#666',
'cursor' : 'none'
});
});
});
$('.test').mouseout(function(){
$(this).css({
'background-color' : '#777',
'cursor' : 'default'
});
});
});
Run Code Online (Sandbox Code Playgroud)
我完全不知道该怎么做,基本上我的代码是这样做的:当你用鼠标输入一个元素并且你的鼠标在该元素内移动时,然后应用这个 CSS,当你的鼠标离开该元素时,然后应用这个 CSS,但是当鼠标位于该元素内并且它停止移动一段时间时,请执行此操作<-我无法弄清楚最后一点。
我知道您想要检测鼠标在特定元素上的移动。
要实现此目的,您需要使用mousemove事件...遗憾的是没有mousefroze事件!
因此,您将使用 asetTimeout()并在鼠标移动时不断清除其回调。由于该事件会在一次轻微的移动中多次触发,因此您可以将延迟设置得非常紧。所以应该是准确的。
setTimeout 回调仅在鼠标停止移动时执行。这就是整个“把戏”。
关于延迟...我认为100ms是最低的准确值。低于此值将会导致用户移动“缓慢”时出现闪烁。
在这里并mouseenter没有多大用处,因为它立即被 mousemove 事件覆盖(因为当鼠标进入时......它也会移动!)。但是mouseleaveormouseout对于恢复元素的原始状态并清除超时确实很有用...因为鼠标不会在元素上移动并不意味着它根本不移动。所以离开的时候一定要弄清楚。
$(document).ready(function() {
var test = $('#test');
var moveTimer;
test.on("mouseout",function(){
$(this).css({
'background-color' : 'white',
}).text("");
clearTimeout(moveTimer);
});
test.on("mousemove",function(){
console.log("I'm moving!");
clearTimeout(moveTimer);
moveTimer = setTimeout(function(){
console.log("I stopped moving!");
test.css({
'background-color' : 'red',
}).text("The mouse is not moving.");
},100)
$(this).css({
'background-color' : 'blue',
}).text("Movement detected...");
});
});Run Code Online (Sandbox Code Playgroud)
#test{
margin:50px;
border:2px solid black;
height:200px;
width:200px;
cursor:pointer;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>Run Code Online (Sandbox Code Playgroud)