相当于 jQuery.draggable() 的原生 JavaScript
是否有相当于 jQuery 的draggable 的原生javascript 代码? 我不需要所有功能,但
- 能够从手柄拖动模式窗口。
- 在开始和结束时 事件,因为我需要在拖动时制作一个覆盖层以防止 鼠标位于模式窗口内的 iframe 上。
- 文档上只有一个可拖动的项目。
Is there a native javascript code equivalent to jQuery's draggable?
I don't need all the features but
- being able to drag a modal window from a handle.
- on start and on end
events as I need to make an overlay layer while dragging to prevent
the mouse being upon the iframe inside the modal window. - there will be only one draggable item on the document.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用事件
dragstart
和dragend
。将模态的位置与鼠标的 x 和 y 坐标联系起来。Use the events
dragstart
anddragend
. Tie the position of the modal relevant to the mouse's x and y coordinates.有 HTML5 dnd api,但由于与我交谈过的人都不喜欢它,而且所有较旧的浏览器都不支持它,所以我想说您在 jQuery 中找到了一个很好的解决方案。
There is the HTML5 dnd api, but since nobody i've talked to liked it in any way and none of the older browsers support it,I would say you found a good solution in jQuery.
使用看起来比 jQuery 更干净的 HTML5 方法:
Use the HTML5 methods which seem cleaner than jQuery's:
尽管问题指出的是原生 JavaScript,但考虑到 @Moe Sweet 评论说 jQuery 已启用,我将做出回应。
拖放是一个特定的事件链。这并不是非常困难,但可能具有挑战性。
简单地说,拖放是以下步骤/事件:
简单的解决方案是使用这些事件:
mousedown
、mousemove
和mouseup
需要注意的一点是,
mousedown
后面的事件需要绑定到window
这样他们就会被抓住如果鼠标在按住时离开了原始元素。代码的“东西”部分是您需要检查元素的屏幕坐标与鼠标的屏幕坐标并适当移动物体的地方。只有在
mousemove
事件期间才真正需要运动,因为在mouseup
或mousedown
事件中鼠标不会移动。有一个类似的问题,其中我发布了 jQuery.dragondrop 插件的代码。
Although the question states native JavaScript, I'm going to respond given that @Moe Sweet commented that jQuery was enabled.
Drag and drop is a particular event chain. It's not obscenely difficult, but it can be challenging.
Simply put, drag and drop is the following steps/events:
The simple solution is to use those events:
mousedown
,mousemove
, andmouseup
A point that should be noticed is that the events following the
mousedown
need to be bound to thewindow
so that they are caught if the mouse has left the original element while being held down.The "stuff" part of the code is where you'll need to check the screen coords of the element vs the screen coords of the mouse and move things appropriately. Motion is only really necessary during the
mousemove
event as the mouse wont have moved for amouseup
ormousedown
event.There is a similar question where I posted my code for a jQuery.dragondrop plugin.