【发布时间】:2020-01-15 08:00:56
【问题描述】:
我正在尝试使用 jQuery animate 使元素在容器 div 的约束内跟随鼠标移动。当鼠标移动时,元素变为具有与其当前位置匹配的绝对定位,然后向鼠标的位置移动,但在 div 内。
但我似乎无法正确定位垂直位置:元素总是高于容器,有时它的移动方向与应有的方向相反(即鼠标向下移动,元素向上移动)。我在水平定位方面没有任何问题。
代码如下:
var executed = false;
var dronePos = $("#drone").offset().top;
$("body").mousemove(function(event) {
var x;
var y;
//Vertical positioning: If the mouse position is greater than or equal to the left offset of the drone container, and less than or equal to the left offset of the drone container plus the width (if it falls within the drone container)
if (event.pageX >= $("#droneContainer").offset().left && event.pageX <= $("#droneContainer").offset().left + $("#droneContainer").width()){
x = event.pageX;
} else { //if it's to the left
if (event.pageX < $("#droneContainer").offset().left){
x = $("#droneContainer").offset().left;
}
else { //if it's to the right
x = $("#droneContainer").offset().left + $("#droneContainer").width();
}
}
//Horizontal positioning: If the mouse position is greater than or equal to the to offset of the drone container, and less than or equal to the top offset of the drone container plus the height (if it falls within the drone container)
if (event.pageY >= $("#droneContainer").offset().top && event.pageY <= $("#droneContainer").offset().top + $("#droneContainer").height()){
y = event.pageY - dronePos;
} else { //if it's above
if (event.pageY < $("#droneContainer").offset().top){
y = $("#droneContainer").offset().top - dronePos;
} else { //if it's below
y = ($("#droneContainer").offset().top + $("#droneContainer").height()) - dronePos;
}
}
if (executed == false){
executed = true;
var position = $("#drone").position();
$("#drone").css({top: position.top, left: position.left, position:"absolute"});
}
$("#drone").stop().animate({
left: x,
top: y
}, 800, "swing");
dronePos = $("#drone").offset().top;
});
非常感谢任何帮助! ????
【问题讨论】:
标签: javascript jquery jquery-animate