【发布时间】:2013-05-28 14:12:53
【问题描述】:
忽略 CSS,它不重要。
这个jQuery 代码的目的是告诉与鼠标进入.container 的方向相反的方向。我知道它看起来很丑陋,但请暂时忽略它。方向为n(北)、ne(东北)等...
现在,如果您像疯子一样打开console 并在div.container 周围移动鼠标,最终您会在console 中看到undefined。 (div.container 是不可见的,并且围绕着圆形按钮)
值undefined只有当getMovementDirection()中的x === 0 && y === 0才可能,这意味着输入div.container时mouse在div.button(球形按钮)内,这是不可能。
那么,我的问题是,这段代码发生了什么?
-感谢您的帮助
PS: 标题需要改进。
jQuery code
(function($) {
var $container = $('div.container'),
$button = $('div.button');
$container.on('mouseenter', function(e) {
var mouseLocation = {
x: e.pageX,
y: e.pageY
}
var buttonLocation = {
x: $button.offset().left,
y: $button.offset().top
}
var loc = getMovementDirection (mouseLocation, buttonLocation, jQuery);
console.log(loc);
});
})(jQuery);
function getMovementDirection (mouse, container, $) {
var width = $('div.button').outerWidth(),
height = $('div.button').outerHeight();
var x, y;
if (mouse.x < container.x) { x = -1; }
else if (mouse.x < container.x + width) { x = 0; }
else { x = 1; }
if (mouse.y < container.y) { y = -1; }
else if (mouse.y < container.y + width) { y = 0; }
else { y = 1; }
if ( x === -1 && y === -1 ) { return 'se'; }
else if ( x === 0 && y === -1 ) { return 's'; }
else if ( x === 1 && y === -1 ) { return 'sw'; }
else if ( x === -1 && y === 0 ) { return 'e'; }
// x === 0 && y === 0 is forbidden
else if ( x === 1 && y === 0 ) { return 'w'; }
else if ( x === -1 && y === 1 ) { return 'ne'; }
else if ( x === 0 && y === 1 ) { return 'n'; }
else if ( x === 1 && y === 1 ) { return 'nw'; }
}
【问题讨论】:
-
这与问题无关,但您正在检查 mouse.y 与 container.y + 宽度而不是 container.y + 高度。我唯一能想到的是从触发事件到捕获鼠标位置数据时鼠标所在位置的轻微延迟。如果有人在您的页面上癫痫发作并在这种情况下使用按钮做其他事情,也许会想出一个案例? :\
-
实际上,我正计划制作那个小游戏,你尝试点击一个按钮,它就会一直逃跑。我知道 jQuery 不是最适合它,但它只是为了好玩。但是这个时间延迟的事情,如果是真的,毁了我所有的计划 :( PS:在这种情况下,容器宽度 = 高度,但感谢纠正我,我忘了改变它