2010-11-12 16 views
25

Sé que esta función:¿Es posible agregar un eventlistener en un DIV?

document.addEventListener('touchstart', function(event) { 
    alert(event.touches.length); 
}, false); 

Pero, ¿es posible añadir a un div? Ejemplo:

document.getElementById("div").addEventListener('touchstart', function(event) { 
     alert(event.touches.length); 
    }, false); 

Aún no lo he probado, tal vez algunos de ustedes lo saben?

+7

¿Por qué no lo intentas tú mismo? –

+3

Porque estoy sentado en el trabajo: P Entonces no puedo probarlo ahora. Estaba almorzando y busqué un poco en él así que ... :) – Roskvist

+0

Sí. Posible. http://www.alistapart.com/articles/domtricks2/ –

Respuesta

34

Sí, así es como lo haces.

document.getElementById("div").addEventListener("touchstart", touchHandler, false); 
document.getElementById("div").addEventListener("touchmove", touchHandler, false); 
document.getElementById("div").addEventListener("touchend", touchHandler, false); 

function touchHandler(e) { 
    if (e.type == "touchstart") { 
    alert("You touched the screen!"); 
    } else if (e.type == "touchmove") { 
    alert("You moved your finger!"); 
    } else if (e.type == "touchend" || e.type == "touchcancel") { 
    alert("You removed your finger from the screen!"); 
    } 
} 

O con jQuery

$(function(){ 
    $("#div").bind("touchstart", function (event) { 
    alert(event.touches.length); 
    }); 
}); 
+0

Muchas gracias :) – Roskvist

+0

El enlace de JQuery también toma el tercer parámetro booleano para manejar el burbujeo. El valor predeterminado es el equivalente de falso en el código de javascript también, por lo que para coherencia debe tenerlo en ambos listados o ninguno. – schilippe

0

La otra forma si no está utilizando addEventListener, probablemente una alternativa para conseguir el control de identificación.

$(document).ready(function() { 
      $('#container1').on("contextmenu", function (e) { 
       e.preventDefault(); 
      }); 
     }); 
Cuestiones relacionadas