This article introduces the implementation steps of JS drag and drop plug-in in detail. It mainly analyzes the following six steps in detail. The specific content is as follows:
1. The principle of js drag and drop plug-in
2. The most basic effect achieved based on the principle
3. Code abstraction and optimization
4. Extension: Effective drag and drop elements
5. Performance optimization and summary
6. jquery plug-in
JS drag and drop is a common web page effect. This article will implement a simple JS plug-in from scratch.
1. The principle of js drag and drop plug-in
What are common drag and drop operations? The whole process probably has the following steps:
1. Click the dragged element with the mouse
2. Press and hold the mouse and move the mouse
3. Drag the element to a certain position and release the mouse
The process here involves three DOM events: onmousedown, onmousemove, onmouseup. So the basic idea of dragging is:
1. Click the dragged element with the mouse to trigger onmousedown
(1) Set the draggability of the current element to true, indicating that it can be dragged
(2) Record the current mouse coordinates x, y
(3) Record the coordinates x,y of the current element
2. Move the mouse to trigger onmousemove
(1) Determine whether the element can be dragged and dropped, if so, go to step 2, otherwise return directly to
(2) If the element can be dragged, set the coordinates of the element
The x-coordinate of the element = the horizontal distance moved by the mouse. The original x-coordinate of the element = the current x-coordinate of the mouse - the x-coordinate before the mouse. The original x-coordinate of the element
The y coordinate of the element = the horizontal distance moved by the mouse. The original y coordinate of the element = the current y coordinate of the mouse - the y coordinate before the mouse. The original y coordinate of the element
3. Release the mouse to trigger onmouseup
(1) Set the draggable state of the mouse to false
Back to top
2. The most basic effect achieved based on the principle
Before realizing the basic effect, there are a few points that need to be explained:
1. If an element wants to be dragged, its postion attribute must be relative or absolute
2. Get the coordinates of the mouse through event.clientX and event.clientY
3. onmousemove is bound to the document element rather than the drag element itself, which can solve the problem of delay or stop movement caused by fast dragging
The code is as follows:
var dragObj = document.getElementById("test"); dragObj.style.left = "px"; dragObj.style.top = "px"; var mouseX, mouseY, objX, objY; var dragging = false; dragObj.onmousedown = function (event) { event = event || window.event; dragging = true; dragObj.style.position = "relative"; mouseX = event.clientX; mouseY = event.clientY; objX = parseInt(dragObj.style.left); objY = parseInt(dragObj.style.top); } document.onmousemove = function (event) { event = event || window.event; if (dragging) { dragObj.style.left = parseInt(event.clientX - mouseX + objX) + "px"; dragObj.style.top = parseInt(event.clientY - mouseY + objY) + "px"; } } document.onmouseup = function () { dragging = false; }
3. Code abstraction and optimization
To make the above code into a plug-in, it needs to be abstracted. The basic structure is as follows:
; (function (window, undefined) {
function Drag(ele) {}
window.Drag = Drag;
})(window, undefined);
First, simply encapsulate some commonly used methods:
; (function (window, undefined) { var dom = { //绑定事件 on: function (node, eventName, handler) { if (node.addEventListener) { node.addEventListener(eventName, handler); } else { node.attachEvent("on" + eventName, handler); } }, //获取元素的样式 getStyle: function (node, styleName) { var realStyle = null; if (window.getComputedStyle) { realStyle = window.getComputedStyle(node, null)[styleName]; } else if (node.currentStyle) { realStyle = node.currentStyle[styleName]; } return realStyle; }, //获取设置元素的样式 setCss: function (node, css) { for (var key in css) { node.style[key] = css[key]; } } }; window.Drag = Drag; })(window, undefined);
The first drag object, which contains an element node and the coordinates x and y before dragging:
function DragElement(node) { this.node = node;//被拖拽的元素节点 this.x = ;//拖拽之前的x坐标 this.y = ;//拖拽之前的y坐标 } DragElement.prototype = { constructor: DragElement, init: function () { this.setEleCss({ "left": dom.getStyle(node, "left"), "top": dom.getStyle(node, "top") }) .setXY(node.style.left, node.style.top); }, //设置当前的坐标 setXY: function (x, y) { this.x = parseInt(x) || ; this.y = parseInt(y) || ; return this; }, //设置元素节点的样式 setEleCss: function (css) { dom.setCss(this.node, css); return this; } }
Another object is the mouse, which mainly contains x coordinates and y coordinates:
function Mouse() { this.x = ; this.y = ; } Mouse.prototype.setXY = function (x, y) { this.x = parseInt(x); this.y = parseInt(y); }
If a page can have multiple drag-and-drop elements, what should you pay attention to:
1. Each element corresponds to a drag object instance
2. Each page can only have one element being dragged
For this purpose, we define a unique object to save the relevant configuration:
var draggableConfig = {
zIndex: ,
draggingObj: null,
mouse: new Mouse()
};
这个对象中有三个属性:
(1)zIndex:用来赋值给拖拽对象的zIndex属性,有多个拖拽对象时,当两个拖拽对象重叠时,会造成当前拖拽对象有可能被挡住,通过设置zIndex使其显示在最顶层
(2)draggingObj:用来保存正在拖拽的对象,在这里去掉了前面的用来判断是否可拖拽的变量,通过draggingObj来判断当前是否可以拖拽以及获取相应的拖拽对象
(3)mouse:唯一的鼠标对象,用来保存当前鼠标的坐标等信息
最后是绑定onmousedown,onmouseover,onmouseout事件,整合上面的代码如下:
; (function (window, undefined) { var dom = { //绑定事件 on: function (node, eventName, handler) { if (node.addEventListener) { node.addEventListener(eventName, handler); } else { node.attachEvent("on" + eventName, handler); } }, //获取元素的样式 getStyle: function (node, styleName) { var realStyle = null; if (window.getComputedStyle) { realStyle = window.getComputedStyle(node, null)[styleName]; } else if (node.currentStyle) { realStyle = node.currentStyle[styleName]; } return realStyle; }, //获取设置元素的样式 setCss: function (node, css) { for (var key in css) { node.style[key] = css[key]; } } }; //#region 拖拽元素类 function DragElement(node) { this.node = node; this.x = ; this.y = ; } DragElement.prototype = { constructor: DragElement, init: function () { this.setEleCss({ "left": dom.getStyle(node, "left"), "top": dom.getStyle(node, "top") }) .setXY(node.style.left, node.style.top); }, setXY: function (x, y) { this.x = parseInt(x) || ; this.y = parseInt(y) || ; return this; }, setEleCss: function (css) { dom.setCss(this.node, css); return this; } } //#endregion //#region 鼠标元素 function Mouse() { this.x = ; this.y = ; } Mouse.prototype.setXY = function (x, y) { this.x = parseInt(x); this.y = parseInt(y); } //#endregion //拖拽配置 var draggableConfig = { zIndex: , draggingObj: null, mouse: new Mouse() }; function Drag(ele) { this.ele = ele; function mouseDown(event) { var ele = event.target || event.srcElement; draggableConfig.mouse.setXY(event.clientX, event.clientY); draggableConfig.draggingObj = new DragElement(ele); draggableConfig.draggingObj .setXY(ele.style.left, ele.style.top) .setEleCss({ "zIndex": draggableConfig.zIndex++, "position": "relative" }); } ele.onselectstart = function () { //防止拖拽对象内的文字被选中 return false; } dom.on(ele, "mousedown", mouseDown); } dom.on(document, "mousemove", function (event) { if (draggableConfig.draggingObj) { var mouse = draggableConfig.mouse, draggingObj = draggableConfig.draggingObj; draggingObj.setEleCss({ "left": parseInt(event.clientX - mouse.x + draggingObj.x) + "px", "top": parseInt(event.clientY - mouse.y + draggingObj.y) + "px" }); } }) dom.on(document, "mouseup", function (event) { draggableConfig.draggingObj = null; }) window.Drag = Drag; })(window, undefined);
调用方法:Drag(document.getElementById("obj"));
注意的一点,为了防止选中拖拽元素中的文字,通过onselectstart事件处理程序return false来处理这个问题。
四、扩展:有效的拖拽元素
我们常见的一些拖拽效果很有可能是这样的:
弹框的顶部是可以进行拖拽操作的,内容区域是不可拖拽的,怎么实现这样的效果呢:
首先优化拖拽元素对象如下,增加一个目标元素target,表示被拖拽对象,在上图的登录框中,就是整个登录窗口。
被记录和设置坐标的拖拽元素就是这个目标元素,但是它并不是整个部分都是拖拽的有效部分。我们在html结构中为拖拽的有效区域添加类draggable表示有效拖拽区域:
拖拽的有效元素
拖拽对象
然后修改Drag方法如下:
function drag(ele) { var dragNode = (ele.querySelector(".draggable") || ele); dom.on(dragNode, "mousedown", function (event) { var dragElement = draggableConfig.dragElement = new DragElement(ele); draggableConfig.mouse.setXY(event.clientX, event.clientY); draggableConfig.dragElement .setXY(dragElement.target.style.left, dragElement.target.style.top) .setTargetCss({ "zIndex": draggableConfig.zIndex++, "position": "relative" }); }).on(dragNode, "mouseover", function () { dom.setCss(this, draggableStyle.dragging); }).on(dragNode, "mouseout", function () { dom.setCss(this, draggableStyle.defaults); }); }
主要修改的是绑定mousedown的节点变成了包含draggable类的有效元素,如果不含有draggable,则整个元素都是有效元素。
五、性能优化和总结
由于onmousemove在一直调用,会造成一些性能问题,我们可以通过setTimout来延迟绑定onmousemove事件,改进move函数如下
function move(event) { if (draggableConfig.dragElement) { var mouse = draggableConfig.mouse, dragElement = draggableConfig.dragElement; dragElement.setTargetCss({ "left": parseInt(event.clientX - mouse.x + dragElement.x) + "px", "top": parseInt(event.clientY - mouse.y + dragElement.y) + "px" }); dom.off(document, "mousemove", move); setTimeout(function () { dom.on(document, "mousemove", move); }, ); } }
总结:
整个拖拽插件的实现其实很简单,主要是要注意几点
1、实现思路:元素拖拽位置的改变就等于鼠标改变的距离,关键在于获取鼠标的变动和元素原本的坐标
2、通过setTimeout来延迟加载onmousemove事件来提供性能
六、jquery插件化
简单地将其封装成jquery插件,主要是相关的dom方法替换成jquery方法来操作
; (function ($, window, undefined) { //#region 拖拽元素类 function DragElement(node) { this.target = node; node.onselectstart = function () { //防止拖拽对象内的文字被选中 return false; } } DragElement.prototype = { constructor: DragElement, setXY: function (x, y) { this.x = parseInt(x) || ; this.y = parseInt(y) || ; return this; }, setTargetCss: function (css) { $(this.target).css(css); return this; } } //#endregion //#region 鼠标元素 function Mouse() { this.x = ; this.y = ; } Mouse.prototype.setXY = function (x, y) { this.x = parseInt(x); this.y = parseInt(y); } //#endregion //拖拽配置 var draggableConfig = { zIndex: , dragElement: null, mouse: new Mouse() }; var draggableStyle = { dragging: { cursor: "move" }, defaults: { cursor: "default" } } var $document = $(document); function drag($ele) { var $dragNode = $ele.find(".draggable"); $dragNode = $dragNode.length > ? $dragNode : $ele; $dragNode.on({ "mousedown": function (event) { var dragElement = draggableConfig.dragElement = new DragElement($ele.get()); draggableConfig.mouse.setXY(event.clientX, event.clientY); draggableConfig.dragElement .setXY(dragElement.target.style.left, dragElement.target.style.top) .setTargetCss({ "zIndex": draggableConfig.zIndex++, "position": "relative" }); }, "mouseover": function () { $(this).css(draggableStyle.dragging); }, "mouseout": function () { $(this).css(draggableStyle.defaults); } }) } function move(event) { if (draggableConfig.dragElement) { var mouse = draggableConfig.mouse, dragElement = draggableConfig.dragElement; dragElement.setTargetCss({ "left": parseInt(event.clientX - mouse.x + dragElement.x) + "px", "top": parseInt(event.clientY - mouse.y + dragElement.y) + "px" }); $document.off("mousemove", move); setTimeout(function () { $document.on("mousemove", move); }, ); } } $document.on({ "mousemove": move, "mouseup": function () { draggableConfig.dragElement = null; } }); $.fn.drag = function (options) { drag(this); } })(jQuery, window, undefined)
以上就是本文对JS拖拽插件实现步骤的详细介绍,希望对大家有所帮助。

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools
