How to use JavaScript to achieve drag and drop effect
Today, the editor will share with you the relevant knowledge about how to use JavaScript to achieve drag and drop effect. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
Drag and drop in front-end development is a very common function, but also one of the basic skills, this article is unlimited drag and drop, that is, the simplest drag, mouse down the object, drag, release stop!
1minute onmousedown event
2 the event of the recorder onmousemove
3Perfect onmouseup event
Because you drag when you press, the onmousemove event is registered after down, and the up event is used to unbind the event and eliminate the event!
Simple drag * {margin: 0; padding: 0;} # div1 {width: 100px; height: 100px; background: orange; position: absolute;} function getStyle (obj, attr) {if (obj.currentStyle) {return obj.currentStyle [attr];} else {return getComputedStyle (obj, null) [attr] }} var oDiv = document.getElementById ('div1'); oDiv.onmousedown = function (ev) {var oEvent = ev | | event; / / var disX = oEvent.clientX-oDiv.offsetLeft; / / var disY = oEvent.clientY-oDiv.offsetTop; var disX = oEvent.clientX-parseInt (getStyle (oDiv,' left'); var disY = oEvent.clientY-parseInt (getStyle (oDiv, 'top')) _ document.onmousemove = function (ev) {var oEvent = ev | | event; oDiv.style.left = oEvent.clientX-disX + 'px'; oDiv.style.top = oEvent.clientY-disY +' px';}; _ document.onmouseup = function () {_ document.onmousemove = null; _ document.onmouseup = null;}; return false;} These are all the contents of the article "how to use JavaScript to achieve drag-and-drop effect". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.