Este artigo apresenta a implementação do elemento arrasto no JavaScript nativo.
Ideias:
1. Primeiro altere os atributos do layout do elemento arrastado, a chave é "posição: absoluto";
2. Capture os eventos do mouse "Mousedown", "Mousemove", "MouseUp";
3. Quando "Mousedown" é acionado, registre a posição relativa do mouse atual no elemento, _x, _y;
4. Em seguida, processe o evento "mousemove" e mova o elemento alterando os atributos superior e esquerdo do elemento;
5. Quando o tempo "MouseUp" é acionado, pare de arrastar.
Ao mesmo tempo, o encapsulamento do código e da compatibilidade do navegador deve ser considerado. O código é o seguinte:
<! Doctype html> <html> <head> <title> draggable div </title> <style type = "text/css"> body {margin: 0; preenchimento: 0; Background-Color: #FFF; } #drag_div {width: 150px; Altura: 150px; preenchimento: 10px; margem: 10px; Background-Color: #66DD33; Cursor: Mova; } </style> </ad Head> </html> <body> <div id = "drag_div"> </div> </body> <script type = "text/javascript"> function drag () {this.initialize.apply (this, argumentos); } Drag.prototype = {// Initialize Initialize: function (elemento, opções) {this.element = this. $ (Elemento); // o objeto sendo arrastado isso._x = this._y = 0; // a posição do mouse no elemento this._movedRag = this.bind (this, this.movedRag); this._stopdrag = this.bind (this, this.stopdrag); // defina o parâmetro this.setOptions (opções); // Defina o objeto "Handle" como "arrastar" com o mouse (observe a diferença do objeto que está sendo arrastado) this.Handle = this. $ (This.options.handle); // defina a função de retorno de chamada this.onstart = this.options.onstart; this.onMove = this.options.onmove; this.onstop = this.options.onstop; this.handle.style.cursor = "move"; this.Changelayout (); // Registre o evento de arrasto inicial this.addhandler (this.handle, "mousedown", this.bind (this, this.startdrag)); }, // altere o atributo do layout do objeto arrastado 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 (); }, MoveRag: 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._movedRag); this.RemoveHandler (documento, "mouseup", this._stopdrag); this.Handle.ReleasecApture && this.handle.releaseCapture (); this.onstop ()}, setOptions: function (options) {this.options = {handle: this.element, // Objeto de evento OnStart: function () {}, // Função de chamando onmove: function () {}, // função de chamada onstop: () {} // Função de chamada {); para (var p nas opções) {this.options [p] = opções [p]; }}, $: function (id) {return typeof id === "string"? document.getElementById (id): id; }, addHandler: function (elemento, eventtype, manipulador) {if (element.addeventListener) {return element.addeventListener (eventtype, manipulador, false); } else {return element.attachevent ("on"+EventType, manipulador); }}, RemowHandler: function (elemento, EventType, Handler) {if (element.RemoveEventListener) {return element.removeEventListener (EventType, Handler, false); } else {return element.Detachevent ("on" + EventType, manipulador); }}, getEvent: function (event) {retornar evento || Window.Event; }, PreventDefault: function (event) {if (event.preventDefault) {event.preventDefault (); } else {event.returnValue = false; }}, bind: function (obj, manipulador) {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>