Los últimos tutoriales de desarrollo web
 

Evento ondrag

<Objeto de evento

Ejemplo

Ejecutar un JavaScript cuando un <p> elemento está siendo arrastrado:

<p draggable="true" ondrag="myFunction(event)">Drag me!</p>
Inténtalo tú mismo "

Más "Try it Yourself" ejemplos a continuación.


Definición y Uso

El evento ondrag se produce cuando está siendo arrastrado un elemento o la selección de texto.

Arrastrar y soltar es una característica muy común en HTML5. Que es cuando se "grab" un objeto y arrastrarlo a una ubicación diferente. Para obtener más información, consulte nuestro Tutorial HTML en HTML 5 de arrastrar y soltar .

Nota: Para que se pueda arrastrar un elemento, utilice el HTML5 mundial pueda arrastrar atributo.

Tip: enlaces y las imágenes se pueden arrastrar por defecto, y no necesitan el draggable atributo.

Hay muchos acontecimientos que se utilizan, y pueden ocurrir, en las diferentes etapas de una operación de arrastrar y soltar:

  • Eventos activados en el objetivo arrastrable (the source element) :
    • ondragstart - se produce cuando el usuario comienza a arrastrar un elemento
    • ondrag - se produce cuando un elemento está siendo arrastrado
    • ondragend - se produce cuando el usuario ha terminado arrastrando el elemento

  • Eventos activados en el destino de colocación:
    • OnDragEnter - se produce cuando el elemento arrastrado entra en el destino de colocación
    • ondragover - se produce cuando el elemento arrastrado se encuentra sobre el destino de colocación
    • OnDragLeave - se produce cuando el elemento arrastrado sale del destino de colocación
    • ondrop - se produce cuando el elemento arrastrado se coloca sobre el destino de colocación

Nota: Al arrastrar un elemento, el evento ondrag dispara cada 350 milisegundos.


Soporte del navegador

Los números de la tabla especifican la primera versión del navegador que es totalmente compatible con el evento.

Evento
ondrag 4.0 9.0 3.5 6.0 12.0

Sintaxis

En HTML:

En JavaScript:

object .ondrag=function(){ Inténtalo tú mismo "

En JavaScript, utilizando el addEventListener() método:

object .addEventListener("drag", myScript );
Inténtalo tú mismo "

Nota: El addEventListener() método no es compatible en Internet Explorer 8 y versiones anteriores.


Detalles técnicos

burbujas:
cancelable:
Tipo de evento: DragEvent
etiquetas HTML admitidas: Todos los elementos HTML
DOM Versión: Nivel 3 Eventos

Ejemplos

Más ejemplos

Ejemplo

Una demostración de todos los posibles eventos de arrastrar y soltar:

<p draggable="true" id="dragtarget">Drag me!</p>

<div class="droptarget">Drop here!</div>

<script>
/* ----------------- Events fired on the drag target ----------------- */

document.addEventListener("dragstart", function(event) {
    // The dataTransfer.setData() method sets the data type and the value of the dragged data
    event.dataTransfer.setData("Text", event.target.id);

    // Output some text when starting to drag the p element
    document.getElementById("demo").innerHTML = "Started to drag the p element.";

    // Change the opacity of the draggable element
    event.target.style.opacity = "0.4";
});

// While dragging the p element, change the color of the output text
document.addEventListener("drag", function(event) {
    document.getElementById("demo").style.color = "red";
});

// Output some text when finished dragging the p element and reset the opacity
document.addEventListener("dragend", function(event) {
    document.getElementById("demo").innerHTML = "Finished dragging the p element.";
    event.target.style.opacity = "1";
});


/* ----------------- Events fired on the drop target ----------------- */

// When the draggable p element enters the droptarget, change the DIVS's border style
document.addEventListener("dragenter", function(event) {
    if ( event.target.className == "droptarget" ) {
        event.target.style.border = "3px dotted red";
    }
});

// By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element
document.addEventListener("dragover", function(event) {
    event.preventDefault();
});

// When the draggable p element leaves the droptarget, reset the DIVS's border style
document.addEventListener("dragleave", function(event) {
    if ( event.target.className == "droptarget" ) {
        event.target.style.border = "";
    }
});

/* On drop - Prevent the browser default handling of the data (default is open as link on drop)
Reset the color of the output text and DIV's border color
Get the dragged data with the dataTransfer.getData() method
The dragged data is the id of the dragged element ("drag1")
Append the dragged element into the drop element
*/
document.addEventListener("drop", function(event) {
    event.preventDefault();
    if ( event.target.className == "droptarget" ) {
        document.getElementById("demo").style.color = "";
        event.target.style.border = "";
        var data = event.dataTransfer.getData("Text");
        event.target.appendChild(document.getElementById(data));
    }
});
</script>
Inténtalo tú mismo "

Páginas relacionadas

HTML Tutorial: Drag and Drop HTML5

Referencia HTML: HTML Atributo arrastrable


Evento de referencia de objetos de objeto de evento