Deshabilitar arrastrar una imagen desde una página HTML


Necesito poner una imagen en mi página. Quiero desactivar el arrastre de esa imagen. Estoy intentando muchas cosas pero sin ayuda. ¿Alguien puede ayudarme ?

No quiero mantener esa imagen como imagen de fondo porque estoy redimensionando la imagen.

Author: User 1034, 2010-11-18

21 answers

Te puede gustar esto...

document.getElementById('my-image').ondragstart = function() { return false; };

Ver que funciona (o no funciona, más bien)

Parece que estás usando jQuery.

$('img').on('dragstart', function(event) { event.preventDefault(); });
 241
Author: alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-27 01:25:28

Solución solo CSS: use pointer-events: none

Https://developer.mozilla.org/en-US/docs/CSS/pointer-events

 138
Author: mikhuang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-21 05:11:23

Simplemente agrega draggable= "false"a tu etiqueta de imagen:

<img draggable="false" src="image.png">

IE8 y bajo no soporta sin embargo.

 108
Author: dmo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-27 17:01:47
window.ondragstart = function() { return false; } 
 38
Author: Ben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-18 05:26:05
img {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-user-drag: none;
  user-drag: none;
  -webkit-touch-callout: none;
}

Lo utilicé en mi sitio web en http://www.namdevmatrimony.in / ¡Funciona como una magia!!! :)

 24
Author: Namdev Matrimony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-10 18:51:04

Lo intenté y encontré que esto está funcionando.

$("img").mousedown(function(){
    return false;
});

Estoy seguro de que esto deshabilita el arrastre de todas las imágenes. No estoy seguro de que afecte a otra cosa.

 22
Author: User 1034,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-18 05:34:02

La solución más simple de navegador cruzado es

<img draggable="false" ondragstart="return false;" src="..." />

Problema con

img {
 -moz-user-select: none;
 -webkit-user-select: none;
 -ms-user-select: none;
 user-select: none;
 -webkit-user-drag: none;
 user-drag: none;
 -webkit-touch-callout: none;
}

Es que no está funcionando en firefox

 16
Author: imal hasaranga perera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-11 12:08:33

Vea esta respuesta ; en Chrome y Safari puede usar el siguiente estilo para deshabilitar el arrastre predeterminado:

-webkit-user-drag: auto | element | none;

Puedes probar user-select para Firefox e IE (10+):

-moz-user-select: none | text | all | element
-ms-user-select: none | text | all | element
 13
Author: mhu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:22

Puedes añadir lo siguiente a cada imagen que no quieras arrastrar, (dentro de la etiqueta img):

onmousedown="return false;"

Por ejemplo

img src="Koala.jpg" onmousedown="return false;"
 11
Author: BOBO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-04 12:37:04

Este código hace exactamente lo que quieres. Evita que la imagen se arrastre mientras permite cualquier otra acción que dependa del evento.

$("img").mousedown(function(e){
    e.preventDefault()
});
 10
Author: Robert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-09 08:14:46

Ya que mis imágenes fueron creadas usando ajax, y por lo tanto no están disponibles en Windows.carga.

$("#page").delegate('img', 'dragstart', function (event) { event.preventDefault(); });

De esta manera puedo controlar qué sección bloquea el comportamiento, solo usa un enlace de eventos y funciona para futuras imágenes creadas por ajax sin tener que hacer nada.

Con jQuery new on enlace:

$('#page').on('dragstart', 'img', function(event) { event.preventDefault(); }); (gracias @ ialphan)

 8
Author: guzart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-03 19:40:37

Usa directamente esto: ondragstart="return false;" en tu etiqueta de imagen.

<img src="http://image-example.png" ondragstart="return false;"/>

Si tiene varias imágenes, envueltas en una etiqueta <div>:

<div ondragstart="return false;">
   <img src="image1.png"/>
   <img scr="image2.png"/>
</div>

Funciona en todos los navegadores principales.

 8
Author: Jan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-02 23:30:00

Gran solución, tenía un pequeño problema con los conflictos, Si alguien más tiene un conflicto de otra biblioteca js, simplemente habilite no conflict like so.

var $j = jQuery.noConflict();$j('img').bind('dragstart', function(event) { event.preventDefault(); });

Espero que esto ayude a alguien.

 4
Author: Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-03 23:04:57

Bueno, no se si las respuestas aquí han ayudado a todos o no, pero aquí hay un simple truco CSS en línea que definitivamente te ayudaría a deshabilitar arrastrar y seleccionar textos en una página HTML.

En tu etiqueta <body> añade ondragstart="return false". Esto deshabilitará el arrastre de imágenes. Pero si también desea desactivar la selección de texto, agregue onselectstart="return false".

El código se verá así: <body ondragstart="return false" onselectstart="return false">

 3
Author: Abhisek Das,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-17 10:21:53
<img draggable="false" src="images/testimg1.jpg" alt=""/>
 3
Author: MurWade,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-20 07:45:31

Bueno, esto es posible, y las otras respuestas publicadas son perfectamente válidas, pero podría tomar un enfoque de fuerza bruta y evitar el comportamiento predeterminado de mousedown en las imágenes. Que, es empezar a arrastrar la imagen.

Algo como esto:

window.onload = function () {  
    var images = document.getElementsByTagName('img');   
    for (var i = 0; img = images[i++];) {    
        img.ondragstart = function() { return false; };
    }  
};  
 2
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-10 17:12:28
document.getElementById('#yourImageId').addEventListener('dragstart', function(e) {
     e.preventDefault();
});

Funciona en este Émbolo http://plnkr.co/edit/HbAbJkF0PVLIMjTmEZml

 2
Author: dtothefp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-26 01:08:46

Puede considerar mi solución la mejor. La mayoría de las respuestas no son compatibles con navegadores antiguos como IE8 ya que e.preventDefault() no será compatible, así como ondragstart evento. Para hacerlo compatible con navegadores hay que bloquear el evento mousemove para esta imagen. Ver ejemplo a continuación:

JQuery

$("#my_image").mousemove( function(e) { return false } ); // fix for IE
$("#my_image").attr("draggable", false); // disable dragging from attribute

Sin jQuery

var my_image = document.getElementById("my_image");
my_image.setAttribute("draggable", false);

if (my_image.addEventListener) {
   my_image.addEventListener("mousemove", function(e) { return false });
} else if (my_image.attachEvent) {
   my_image.attachEvent("onmousemove", function(e) { return false });
}

Probado y trabajado incluso para IE8

 2
Author: CodeGems,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-12 10:27:57

Establezca las siguientes propiedades CSS en la imagen:

user-drag: none; 
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
 2
Author: Omid Farvid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-12 10:51:12

Robando de mi propia respuesta, simplemente agregue un elemento completamente transparente del mismo tamaño sobre la imagen. Cuando cambie el tamaño de la imagen, asegúrese de cambiar el tamaño del elemento.

Esto debería funcionar para la mayoría de los navegadores, incluso los más antiguos.

 -1
Author: Sablefoste,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:59

Hice las propiedades css que se muestran aquí, así como monitorear ondragstart con el siguiente javascript:

handleDragStart: function (evt) {
    if (evt.target.nodeName.match(/^(IMG|DIV|SPAN|A)$/i)) {
      evt.preventDefault();
      return false;
    }
  },
 -1
Author: Alocus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-07 14:31:20