问题
I'm trying to detect three mouse movement states in this (modified) jQuery plugin – left, right and stop (mouse not moving):
(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>");
});
});
But it doesn't work as expected. I believe there should be some kind of minimal delay between firing of subsequent checks in mousemove
function but I'm not sure how to implement it.
http://jsfiddle.net/fallenartist/7pBE7/1/ - mostly in 'stop' state, not detecting properly 'left' and 'right' mouse movement
Thanks a million.
回答1:
As per Pedro's solution above, this answers my question:
(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>");
});
});
http://jsfiddle.net/fallenartist/7pBE7/5/
来源:https://stackoverflow.com/questions/16974178/detecting-both-left-and-right-mouse-movement-and-no-movement