可拖动对象背后的技术是什么?
我正在尝试学习如何通过纯 JavaScript 而不是使用外部库来使 HTML 页面中的 div 可拖动,因此我尝试了一些技术,但未能使其成为适当的可拖动对象。我确信我的代码中遗漏了一些重要的东西,所以我想知道可拖动对象背后的基本思想是什么。我试图通过设置一些 startX 和 startY 位置并使 Div 位置绝对并通过 css 设置 div 的左侧和顶部来实现它
p.style.left = (e.clientX-startX) + 'px';
p.style.top = (e.clientY-startY) + 'px';
// where p is the element i am trying to make draggable
I am trying to learn how to make a div in an HTML page draggable by pure JavaScript not by using external library so I tried some of mine techniques but I failed to make it a proper draggable object. I am sure I'm missing something important in my code so I want to know what is the basic idea behind draggable object. I was trying to achieve it by setting some startX and startY position and making the Div position absolute and setting the left and top of div by css as
p.style.left = (e.clientX-startX) + 'px';
p.style.top = (e.clientY-startY) + 'px';
// where p is the element i am trying to make draggable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应忘记保存
p
的初始位置并每次添加它,以确保您正在进行相对计算。目前,您假设开始拖动时p
始终位于(0, 0)
位置。其次,取消
selectstart
事件可以避免在拖动时创建丑陋的选择。我对您的代码进行了一些更新: http://jsfiddle.net/rLegF/1/ 。
编辑:您还可以结合使用
startX
和origX
,因为您基本上总是在做- startX + origX
:< a href="http://jsfiddle.net/rLegF/2/" rel="nofollow">http://jsfiddle.net/rLegF/2/。然后,您要做的就是计算鼠标相对于元素左上角的位置,然后将该位置设置为新的鼠标位置减去旧的鼠标位置。也许这样更直观一些。
我也清理了一些。
You should not forget to save
p
's initial position and add it each time to make sure you're doing relative calculations. Currently, you assumep
is always at position(0, 0)
when starting dragging.Secondly, cancelling the
selectstart
event makes for no ugly selection being created when dragging.I updated your code a bit to this effect: http://jsfiddle.net/rLegF/1/.
Edit: You could also combine
startX
andorigX
since you're basically always doing- startX + origX
: http://jsfiddle.net/rLegF/2/.What you're then doing is calculating the mouse position with respect to the top left-hand corner of the element, and then set the position to the new mouse position minus that old mouse position. Perhaps it's a little more intuitive that way.
I cleaned up some more as well.