gpt4 book ai didi

jquery - 检测鼠标左右移动和无移动

转载 作者:行者123 更新时间:2023-12-01 03:42:54 25 4
gpt4 key购买 nike

我正在尝试检测此(已修改)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/ - 主要处于“停止”状态,无法正确检测“左”和“右”鼠标移动

感谢一百万。

最佳答案

根据上面佩德罗的解决方案,这回答了我的问题:

(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/

关于jquery - 检测鼠标左右移动和无移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16974178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com