Este artículo introduce la implementación de Element Drag en JavaScript nativo.
Ideas:
1. Primero cambie los atributos de diseño del elemento arrastrado, la clave es "Posición: Absolue";
2. Capture los eventos del ratón "Mousedown", "mouseMove", "mouseup";
3. Cuando se activa "MouseDown", registre la posición relativa del mouse actual en el elemento, _x, _y;
4. Luego procese el evento "mouseMove" y mueva el elemento cambiando los atributos superior e izquierdo del elemento;
5. Cuando se active el tiempo "Mouseup", deje de arrastrar.
Al mismo tiempo, se debe considerar la encapsulación del código y la compatibilidad del navegador. El código es el siguiente:
<! Doctype html> <html> <fead> <title> draggable div </title> <style type = "text/css"> cuerpo {margen: 0; relleno: 0; Color de fondo: #fff; } #drag_div {ancho: 150px; Altura: 150px; relleno: 10px; margen: 10px; Color de fondo: #66DD33; cursor: mover; } </style> </head> </html> <body> <div id = "drag_div"> </div> </body> <script type = "text/javaScript"> function drag () {this.initialize.apply (this, argumentos); } Drag.prototype = {// inicializar inicialize: function (element, options) {this.element = this. $ (Elemento); // El objeto que se está arrastrando this._x = this._y = 0; // La posición del mouse en el elemento this._movegrag = this.bind (this, this.moveDrag); this._stopdrag = this.bind (this, this.stopdrag); // Establecer el parámetro this.setOptions (opciones); // Establezca el objeto "Handle" a "arrastrar" con el mouse (tenga en cuenta la diferencia del objeto que se está arrastrando) this.handle = this. $ (This.options.handle); // Establecer la función de devolución de llamada this.onstart = this.options.onstart; this.onmove = this.options.Onmove; this.onstop = this.options.onstop; this.handle.style.cursor = "Move"; this.changelayout (); // Registre el evento de arranque de inicio this.addhandler (this.handle, "MouseDown", this.bind (this, this.startdrag)); }, // Cambie el atributo de diseño del objeto arrastrado ChangelayOut: function () {this.element.style.top = this.element.offsettop + "px"; this.element.style.left = this.element.offsetleft + "px"; this.element.style.position = "Absolute"; this.element.style.Margin = "0"; }, startDrag: function (event) {var event = event || Window.event; this._x = event.clientx - this.element.offsetleft; this._y = event.clienty - this.element.offsettop; this.addhandler (documento, "mouseMove", this._moveDrag); this.addhandler (documento, "mouseup", this._stopdrag); this.PreventDefault (evento); this.handle.setCapture && this.handle.setCapture (); this.onstart (); }, MovedRag: function (event) {var event = this.getEvent (evento); var iTop = event.clienty - this._y; var ileft = event.clientx - this._x; this.element.style.top = iTop + "Px"; this.element.style.left = ILeft + "Px"; this.Onmove (); }, stopDrag: function () {this.removeHandler (documento, "mouseMove", this._movegrag); this.removeHandler (documento, "mouseup", this._stopdrag); this.handle.ReleaseCapture && this.handle.ReleaseCapture (); this.onstop ()}, setOptions: function (options) {this.options = {handle: this.element, // event object onStart: function () {}, // llamando a function onmove: function () {}, // llamando a la función en function: function () {} // llamando a la función oncalp: function () {} // llamando a la función °p}; for (var p en opciones) {this.options [p] = options [p]; }}, $: function (id) {return typeOf id === "cadena"? document.getElementById (id): id; }, addHandler: function (element, eventType, handler) {if (element.addeventListener) {return element.adDeventListener (eventtype, handler, falso); } else {return element.attachevent ("on"+eventtype, handler); }}, removeHandler: function (element, eventType, handler) {if (element.removeEventListener) {return element.removeEventListener (eventType, handler, falso); } else {return element.detachevent ("on" + eventtype, manejador); }}, getEvent: function (event) {return Event || Window.event; }, PreventDefault: function (event) {if (event.preventDefault) {event.preventDefault (); } else {event.returnValue = false; }}, bind: function (obj, handler) {return function () {return handler.apply (obj, argumentos); }}}}; Window.Onload = function () {var drag_div = document.getElementById ("drag_div"); var drag = new Drag (drag_div, {handle: drag_div}); } </script> </html>