我正在尝试检测此(修改的)jQuery plugin中的三个鼠标移动状态 - 左,右和停止(鼠标不移动):
(function ($) {
var options = {};
var oldx = 0;
var direction = "";
$.mousedirection = function (opts) {
var defaults = {};
options = $.extend(defaults, opts);
$(document).bind("mousemove", function (e) {
var activeElement = e.target || e.srcElement;
if (e.pageX == oldx) {
direction = "stop";
} else if (e.pageX > oldx) {
direction = "right";
} else if (e.pageX < oldx) {
direction = "left";
}
$(activeElement).trigger(direction);
$(activeElement).trigger({
type: "mousedirection",
direction: direction
});
oldx = e.pageX;
});
}
})(jQuery)
$(function () {
$.mousedirection();
$(".container").bind("mousedirection", function (e) {
$(this).html("Mouse Direction: <b>" + e.direction + "</b>");
});
});
但它没有按预期工作。我相信在mousemove
函数中触发后续检查之间应该存在某种最小延迟,但我不确定如何实现它。
http://jsfiddle.net/fallenartist/7pBE7/1/ - 大部分处于“停止”状态,未正确检测到“左”和“右”鼠标移动
万分感谢。
答案 0 :(得分:3)
根据Pedro的解决方案,这回答了我的问题:
(function ($) {
var options = {};
var oldx = 0;
var direction = "";
var stop_timeout = false;
var stop_check_time = 150;
$.mousedirection = function (opts) {
var defaults = {};
options = $.extend(defaults, opts);
$(document).bind("mousemove", function (e) {
var activeElement = e.target || e.srcElement;
if (e.pageX > oldx) {
direction = "right";
} else if (e.pageX < oldx) {
direction = "left";
}
clearTimeout(stop_timeout);
stop_timeout = setTimeout(function () {
direction = "stop";
$(activeElement).trigger(direction);
$(activeElement).trigger({
type: "mousedirection",
direction: direction
});
}, stop_check_time);
$(activeElement).trigger(direction);
$(activeElement).trigger({
type: "mousedirection",
direction: direction
});
oldx = e.pageX;
});
}
})(jQuery)
$(function () {
$.mousedirection();
$(".container").bind("mousedirection", function (e) {
$(this).html("Mouse Direction: <b>" + e.direction + "</b>");
});
});