gpt4 book ai didi

javascript - 在 JavaScript 中拖放

转载 作者:行者123 更新时间:2023-11-28 07:39:57 25 4
gpt4 key购买 nike

我正在尝试在 JavaScript 中实现拖放功能。我几乎已经完成了这个任务,但是当 mousemove 事件被触发时,问题就出现了。该元素未到达指针的位置。我尝试了很多事情但无法正确设置。这是link of my code 。我也在这里提到我的代码结构:

HTML:

<div class="pillers">
<div class="dragable">Randome tet</div>
<div class="dragable">Randome tet</div>
<div class="dragable">Randome tet</div>
<div class="dragable">Randome tet</div>
</div>
<div class="pillers"></div>
<div class="pillers"></div>
<div class="pillers"></div>

JS:

var mouseX = 0,
mouseY = 0,
elmX = 0,
elmY = 0,
tempZ = 0,
currentElm;

$(document).on('mousedown', '.dragable', function(e){
var temp;
$(this).addClass('abs');

mouseX = e.clientX;
mouseY = e.clientY;

temp = +($(this).css('left'));
//temp = $(this).offset().left;
elmX = null || isNaN(temp) ? 0 : temp;

temp = +($(this).css('top'));
//temp = $(this).offset().top
elmY = null || isNaN(temp) ? 0 : temp;

$(this).css({'z-index':'9999'});

currentElm = $(this);

document.body.focus();
// prevent text selection in IE
document.onselectstart = function () { return false; };

// prevent IE from trying to drag an image
$(this).ondragstart = function() { return false; };

// prevent text selection (except IE)
return false;
}).mouseup('.dragable', function(e){
if(currentElm !== null){
currentElm.css({'z-index' : '1'});
currentElm = null;
}
}).mousemove('.dragable', function(e){
if(currentElm !== null){
currentElm.css({
left : (elmX + e.clientX - mouseX)+'px',
top : (elmY + e.clientY - mouseY)+'px'
});
}
});

拖动项目未正确设置其位置。这是Link for Codepen

还有一件事...如果我想在 mouseup 事件中检查鼠标目标是否为 pillers 类,应该是什么条件。

最佳答案

在 mousedown 事件的函数中没有正确声明元素的位置;它们总是为零,上面。

因为这些值是声明的元素的起始坐标,所以在鼠标按下时,元素将移动到屏幕的左上角 (0,0)。

上面的 elmX 和 elmY 部分可以替换为以下内容:

elmX = $(this).offset().left;
elmY = $(this).offset().top;

这使得起始坐标成为鼠标按下时的实际起始位置。

此更改在 Chrome 中对我有用。更新了CodePen .

关于javascript - 在 JavaScript 中拖放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28180330/

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