gpt4 book ai didi

jQuery:鼠标移动事件 - 元素内向左、向右

转载 作者:行者123 更新时间:2023-11-30 23:50:26 29 4
gpt4 key购买 nike

我想获取div的鼠标坐标,如下所示:

$("#box").mousemove(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;

document.getElementById("coords").innerHTML = x + ", " + y; });

但我也希望能够判断光标是向左还是向右移动;我知道我只需将当前鼠标位置与前一个鼠标位置进行比较,但我不知道在这种情况下该怎么做。

任何帮助表示赞赏。谢谢

最佳答案

获取鼠标位置的jquery代码如下

jQuery(document).ready(function(){

$(document).mousemove(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})

显然你必须有一个名为“status”的 div

<div id="status">0, 0</div>

要检查光标是否向左或向右移动,您必须存储之前的位置,然后将其与新位置进行比较。

我在这里给你写了完整的例子:

http://jsfiddle.net/cB9Wq/

_ 编辑:

如果您需要获取 div 内的坐标,您还需要知道 div 的位置:

$(".div_container").mousemove(function(e){
var relativeXPosition = (e.pageX - this.offsetLeft); //offset -> method allows you to retrieve the current position of an element 'relative' to the document
var relativeYPosition = (e.pageY - this.offsetTop);
$("#header").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
}).mouseout(function(){
$("#header").html("<p>Move mouse on the below blue div container! :)</p>")
});

为了检查鼠标是否向左或向右移动,我使用了以下语法:

xPrev<e.pageX ? $('#lr').html("right") : $('#lr').html("left");
xPrev=e.pageX;

注意:这相当于:

if(xPrev<e.pageX) { 
$('#lr').html("right");
}
else {
$('#lr').html("left");
}
xPrev=e.pageX;

这里有工作示例:http://jsfiddle.net/cB9Wq/2/

关于jQuery:鼠标移动事件 - 元素内向左、向右,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14047801/

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