JavaScript Drag and Drop Tutorial

本文介绍了一个简洁易懂的JavaScript拖拽教程,通过简单的代码实现HTML元素的拖动功能,并讨论了浏览器兼容性和鼠标按钮的使用。

Try dragging one of the items below:


Item 1 is <div>
Item 2 is <div>
drag image
NON-draggable element clicked

Introduction


由于没有太好的关于如何用javascript实现拖拽

Because I found no succinct and understandable tutorials on how to implementdrag and drop with javascript, I came up with the below.  Credit where  is due:I used a devarticles.com article to generate this single-page tutorial; the article discussesgeneral drag and drop issues.

Drag and drop is a topic that can be explored to great lengths somewhere else; allyou need to know about it here is that you left-click-and-hold on one "draggable element",and then move your mouse with the left button down: the element you clicked on followsyour mouse.  Restrictions on what can be dragged and where it can be dragged arediscussed briefly.  If you know about a better tutorial on this topic, or have suggestions, please let me know!  Quirksmode now hasa drag and drop tutorial, althoughit is quite a bit longer than this one.  Go there for completness, stay here for succinctness.

Draggable Elements


The following javascript will allow dragging html elements with class="drag". The only required css is:

.drag { position: relative; }

Global Variables


Quite a few global variables are required to make things possible:

var _startX = 0; // mouse starting positionsvar _startY = 0;var _offsetX = 0; // current element offsetvar _offsetY = 0;var _dragElement; // needs to be passed from OnMouseDown to OnMouseMovevar _oldZIndex = 0; // we temporarily increase the z-index during dragvar _debug = $('debug'); // makes life easier

JavaScript Events


The relevant events belong to the document: onMouseDown, onMouseMove, and onMouseUp.  Attempting to make drag and drop using onMouseMoveof an element will result in buggy operation, as the cursor tends to jump outside of the elementwhen it is moved quickly; when this happens, onMouseMove will stop firing until themouse moves back over the element. Clearly, this is not desirable, so the document's mouse eventsare used.

Two events are initialized here:

InitDragDrop();function InitDragDrop(){ document.onmousedown = OnMouseDown; document.onmouseup = OnMouseUp;}

We start with onMouseDown:

function OnMouseDown(e){ // IE is retarded and doesn't pass the event object if (e == null) e = window.event; // IE uses srcElement, others use target var target = e.target != null ? e.target : e.srcElement; _debug.innerHTML = target.className == 'drag' ? 'draggable element clicked' : 'NON-draggable element clicked'; // for IE, left click == 1 // for Firefox, left click == 0 if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') { // grab the mouse position _startX = e.clientX; _startY = e.clientY; // grab the clicked element's position _offsetX = ExtractNumber(target.style.left); _offsetY = ExtractNumber(target.style.top); // bring the clicked element to the front while it is being dragged _oldZIndex = target.style.zIndex; target.style.zIndex = 10000; // we need to access the element in OnMouseMove _dragElement = target; // tell our code to start moving the element with the mouse document.onmousemove = OnMouseMove; // cancel out any text selections document.body.focus(); // prevent text selection in IE document.onselectstart = function () { return false; }; // prevent IE from trying to drag an image target.ondragstart = function() { return false; }; // prevent text selection (except IE) return false; }}

The comments cover just about everything; the "text selection" stuff existsbecause we want to avoid selecting text when dragging things around.  OnceOnMouseMove is wired up, it will fire whenever the mouse moves:

function OnMouseMove(e){ if (e == null) var e = window.event; // this is the actual "drag code" _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px'; _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; _debug.innerHTML = '(' + _dragElement.style.left + ', ' + _dragElement.style.top + ')'; }

When the mouse is released, we remove the event handlers and reset _dragElement:

function OnMouseUp(e){ if (_dragElement != null) { _dragElement.style.zIndex = _oldZIndex; // we're done with these events until the next OnMouseDown document.onmousemove = null; document.onselectstart = null; _dragElement.ondragstart = null; // this is how we know we're not dragging _dragElement = null; _debug.innerHTML = 'mouse up'; }}

Utility Functions


function ExtractNumber(value){ var n = parseInt(value); return n == null || isNaN(n) ? 0 : n;}// this is simply a shortcut for the eyes and fingersfunction $(id){ return document.getElementById(id);}

Some Things to Consider


This example only scratches the surface of drag and drop.  For example, dragging isoften only initiated if the user clicks and drags the mouse more than a pixel for two(to prevent jitter or something, it's a common practice).  Moreover, one often wantsto drag from one place to another, instead of just randomly.  Keep on the lookoutfor a more advanced drag and drop tutorial covering these sorts of things.  Simplicity first!

Determining what elements one is dragging over is tricky, because the onmouseoverevent does not fire if the cursor is over the element being dragged.  The only solution[known to the author] is to look for elements under the cursor by position.  position.jsfrom the Prototype javascript library demonstratesthe requirements for doing this.  Determining the Droppable provides a nice overview of this process.

The code presented blatantly overwrites any existing event handlers.  If other javascriptneeds to deal with these events, one should investigate attachEvent, or moregenerally, event handling in Javascript.

<iframe />


I have not tested this, but apparently event.screenX and event.screenY should be used instead ofclientX and clientY if one is using iframes.

Mouse Buttons


Because browser makers love incompatibility, the codes for event.button vary from browser to browser; see the below table for values and feel free to provide me with additional rows for other browsers.

BrowserLeft ClickMiddle ClickRight Click
Firefox012
Internet Explorer142

Note that IE uses the values 1, 2, and 4 so that one can determine every mouse buttonthat is pressed; Firefox does not allow this.

Browser compatibility


This example has only been tested in IE6&7, Firefox 3.0.5, Opera 9.2+, and Chrome 2.0; results from testing in other browsers would be appreciated.

Support Tutorials like This


If you found this tutorial helpful, please link to it.  If you really want to show your appreciation... :-)


STM32电机库无感代码注释无传感器版本龙贝格观测三电阻双AD采样前馈控制弱磁控制斜坡启动内容概要:本文档为一份关于STM32电机控制的无传感器版本代码注释资源,聚焦于龙贝格观测器在永磁同步电机(PMSM)无感控制中的应用。内容涵盖三电阻双通道AD采样技术、前馈控制、弱磁控制及斜坡启动等关键控制策略的实现方法,旨在通过详细的代码解析帮助开发者深入理解基于STM32平台的高性能电机控制算法设计与工程实现。文档适用于从事电机控制开发的技术人员,重点解析了无位置传感器控制下的转子初始定位、速度估算与系统稳定性优化等问题。; 适合人群:具备一定嵌入式开发基础,熟悉STM32平台及电机控制原理的工程师或研究人员,尤其适合从事无感FOC开发的中高级技术人员。; 使用场景及目标:①掌握龙贝格观测器在PMSM无感控制中的建模与实现;②理解三电阻采样与双AD同步采集的硬件匹配与软件处理机制;③实现前馈补偿提升动态响应、弱磁扩速控制策略以及平稳斜坡启动过程;④为实际项目中调试和优化无感FOC系统提供代码参考和技术支持; 阅读建议:建议结合STM32电机控制硬件平台进行代码对照阅读与实验验证,重点关注观测器设计、电流采样校准、PI参数整定及各控制模块之间的协同逻辑,建议配合示波器进行信号观测以加深对控制时序与性能表现的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值