我的问题很简单。当我的鼠标移动时,我想执行一个在div
标签中打印"you are moving"
的函数。当我的鼠标不动时,我希望文本功能消失。下面是我能想到的伪代码。例如,text函数将每隔50/1000秒调用一次,并检查鼠标是否在移动。如果它在移动,文本将会显示。如果鼠标没有移动,文本将不会显示。既然没有mousestop事件,我该如何实现这一点呢?
$(function() { setInterval(text, 50);
});
function text() {
/*Do something to check if mouse is moving*/
/*if mouse is moving*/
if{
$("#shu").text("You are moving");
} else {
$("#shu").remove();
}
}
发布于 2016-06-23 15:36:53
纯javascript解决方案:
var shu = document.getElementById("shu");
var timeout;
document.addEventListener("mousemove", function() {
shu.innerHTML = "You are moving";
if (timeout) clearTimeout(timeout);
timeout = setTimeout(mouseStop, 150);
});
function mouseStop() {
shu.innerHTML = "";
}
发布于 2016-06-23 15:28:24
$(window).mousemove(
function() {
$("#shu").text("You are moving");
}, function() {
$("#shu").remove();
}
);
发布于 2016-06-23 15:30:01
您可以使用jQuery .mousemove
函数和设置间隔来检查鼠标的移动。
下面是一个示例代码。
var lastTimeMouseMoved = "";
jQuery(document).ready(function(){
$(document).mousemove(function(e){
$(".text").show();
lastTimeMouseMoved = new Date().getTime();
var t=setTimeout(function(){
var currentTime = new Date().getTime();
if(currentTime - lastTimeMouseMoved > 1000){
$('.text').fadeOut('fast');
}
},1000)
});
});
body{
background-color:#333;
}
.text{
display:none;
color:white;
font-size:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Your are moving!!</div>
https://stackoverflow.com/questions/37984771
复制相似问题