当鼠标闲置x倍的时间时,我试图使用jquery在鼠标的位置上创建一个新的div。如果它保持空闲状态,则div的大小将增加。当我移动鼠标时,创建的新div仍将保留。我将如何使用下面附带的jquery进行此操作?我认为应该遵循相同的逻辑?非常感谢。
idleTimer = null;
idleState = false;
idleWait = 2000;
(function ($) {
$(document).ready(function () {
$('*').bind('mousemove keydown scroll', function () {
clearTimeout(idleTimer);
if (idleState == true) {
// Reactivated event
$("body").append("<p>Welcome Back.</p>");
}
idleState = false;
idleTimer = setTimeout(function () {
// Idle Event
$("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");
idleState = true; }, idleWait);
});
$("body").trigger("mousemove");
});
}) (jQuery)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 0 :(得分:1)
您将需要一个间隔来检查空闲状态。我的示例可能不是您想要的100%,但是您应该可以根据自己的喜好进行调整。
var idleTimer = null;
var idleState = false;
var idleWait = 2000;
var idleInterval = 1000;
var idleStartTime = Date.now();
var mouseX = 0;
var mouseY = 0;
(function($) {
$(document).ready(function() {
//Set a interval that checks the idle state
setInterval(function() {
if (idleState == true) {
//add element if it doensn't excist, otherwise update it
if ($('#idleDiv').length === 0) {
var $el = $('<div>');
$el.attr('id', 'idleDiv');
$el.css('left', mouseX);
$el.css('top', mouseY);
$el.html('<p>You\'ve been idle for ' + ((Date.now() - idleStartTime) / 1000) + ' seconds.</p>');
$("body").append($el);
} else {
$('#idleDiv').html('<p>You\'ve been idle for ' + ((Date.now() - idleStartTime) / 1000) + ' seconds.</p>');
}
//change the height when idle
$('#idleDiv').height($('#idleDiv').height() + 10);
}
}, idleInterval);
//sets the idleState to false on mousemove events and to true when no mouse move happended for 'idleWait' milliseconds.
$(document).on('mousemove', function(event) {
idleStartTime = Date.now();
idleState = false;
clearTimeout(idleTimer);
idleTimer = setTimeout(function() {
idleState = true
}, idleWait);
//Set the mouse coordinates
mouseX = event.pageX;
mouseY = event.pageY;
});
});
})(jQuery)
html,
body {
padding: 0px;
margin: 0px;
}
#idleDiv {
background-color: gray;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 1 :(得分:-1)
我建议执行以下步骤:
var elem =“”; $(div).append(elem); lastElem = $(div).last();
我在这里概述了要点,您可以通过研究来获得实际的代码...它们都可以在Internet上获得。
希望有帮助。