Learn to use JS drag and drop components_javascript skills
JS code needs to be written often, otherwise it will be easy to get rusty. Recently, although I have been looking at JS prototypes, behavioral delegation and other knowledge points, the amount of hands-on code writing has been slightly reduced. This article shares a drag and drop component with you for your reference. The specific content is as follows
First, let’s take a look at the principle of dragging.
The change in the position of the dragged element and the left value are actually the change in the horizontal direction of the mouse position, e.clientX - e.clientX when the left mouse button is pressed.
The change in the top value is actually the change in the vertical direction of the mouse position, e.clientY - e.clientY when the left mouse button is pressed.
The other is to set the dragging range . The top, bottom, left and right should not exceed the area where the parent element is located.
function Drag (config){ this.moveTarget = document.getElementById(config.id); if(config.parentId){ this.targetParent = document.getElementById(config.parentId); this.max_left = this.targetParent.clientWidth - this.moveTarget.offsetWidth; this.max_top = this.targetParent.clientHeight - this.moveTarget.offsetHeight; }else{ console.log(document.documentElement.clientHeight + "||" + this.moveTarget.offsetHeight) this.max_left = document.documentElement.clientWidth - this.moveTarget.offsetWidth - parseInt(this.getStyle(document.body, "border-width")); this.max_top = document.documentElement.clientHeight - this.moveTarget.offsetHeight- parseInt(this.getStyle(document.body, "border-width")); } this.lock = true; } Drag.prototype.getStyle = function(element, attr){ if(element.currentStyle){ return element.currentStyle[attr]; }else{ return window.getComputedStyle(element,null).getPropertyValue(attr) } } Drag.prototype.moDown = function(e){ e = e || window.event; this.clientX = e.clientX; this.clientY = e.clientY; //鼠标按下时,drag的left值,top值(写在style中或者是css中) this.startLeft = parseInt(this.moveTarget.style.left || this.getStyle(this.moveTarget, "left")); this.startTop = parseInt(this.moveTarget.style.top || this.getStyle(this.moveTarget, "top")); //鼠标按下时,鼠标的clientX值,clientY值 this.startClientX = e.clientX; this.startClientY = e.clientY; this.lock = false; }; Drag.prototype.moMove = function(e){ e = e || window.event; if(e.which != 1){ this.lock = true; } if(!this.lock){ var realLeft = this.startLeft + e.clientX - this.startClientX;//实际的移动范围 var realTop = this.startTop + e.clientY - this.startClientY; //rightLeft , rightTop; //left, top 取值(在可移动范围内) var rightLeft = realLeft > this.max_left ? this.max_left : ( realLeft > 0 ? realLeft : 0 ); var rightTop = realTop > this.max_top ? this.max_top : ( realTop > 0 ? realTop : 0 ); this.moveTarget.style.left = rightLeft + "px"; this.moveTarget.style.top = rightTop + "px"; } }; Drag.prototype.moUp = function(e){ e = e || window.event; this.lock = true; }; Drag.prototype.startDrag = function(){ console.log(this) this.moveTarget.onmousedown = function(e){this.moDown(e)}.bind(this); this.moveTarget.onmousemove = function(e){this.moMove(e)}.bind(this); this.moveTarget.onmouseup = function(e){this.moUp(e)}.bind(this); }
Description: moDown responds to the left mouse button press operation, moMove responds to the mouse move operation, and MoUp responds to the mouse lift operation.
Added e.which judgment in moMove, e.which ==1 means the left mouse button is pressed. This is to solve the problem that when the mouse is moved outside the draggable range, there is no need to press the left button when moving back. , there is a bug that the dragged element will move accordingly.
Instructions for use:
When used, the id of the dragged element is a required parameter, and the id of the parent element (that is, the range that can be dragged and moved) is an optional parameter. If the id of the parent element is not passed, documentElement is used by default to be draggable. The range of pulling.
If you pass a parent element, don’t forget to set the positioning of the parent element to position:relative or position:absolute.
When using it, first introduce the js file of the drag and drop plug-in.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content="刘艳"> <meta name="Keywords" content="关键字"> <meta name="Description" content="描述"> <title>Document</title> <style> *{ margin:0px; padding:0px; } #content{ width:600px; height:500px; position:relative; border:5px solid green; } #drag{ position:absolute; height:100px; width:100px; top:50px;left:0px; background:pink; cursor:pointer; } </style> </head> <body> <div id = "content"> <div id = "drag" > </div> </div> </body> </html> <script src = "url/drag.js"></script> <script> window.onload = function(){ var drag = new Drag({id: "drag", parentId: "content"}); drag.startDrag(); } </script>
If you want to drag across the entire window, please do not set the positioning of the parent element of the dragged element, that is, position it relative to the body.
If you need to position the body, but also need to set the position of its parent element to non-static, then you can extend this plug-in.
I hope this article will be helpful to everyone in learning javascript programming.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use JavaScript to implement the drag and zoom function of images? In modern web development, dragging and zooming images is a common requirement. By using JavaScript, we can easily add dragging and zooming functions to images to provide a better user experience. In this article, we will introduce how to use JavaScript to implement this function, with specific code examples. HTML structure First, we need a basic HTML structure to display pictures and add

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese
