Evento onclick

Definición y uso

El evento onclick ocurre cuando el usuario hace clic en un elemento.

实例

Ejecute JavaScript al hacer clic en el botón:

<button onclick="myFunction()">Haga clic aquí</button>

Prueba por ti mismo

En la parte inferior de la página hay más ejemplos de TIY.

Sintaxis

En HTML:

<elemento onclick="myScript">

Prueba por ti mismo

En JavaScript:

objeto.onclick = function(){myScript};

Prueba por ti mismo

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

objeto.addEventListener("click", myScript);

Prueba por ti mismo

Notas:Internet Explorer 8 y versiones anteriores no admiten Método addEventListener().

Detalles técnicos

Burbuja: Soporte
Cancelables: Soporte
Tipos de eventos: MouseEvent
Etiquetas HTML admitidas: Todos los elementos HTML, excepto: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> y <title>
Versión del DOM: Eventos de Nivel 2

Compatibilidad del navegador

Evento Chrome IE Firefox Safari Opera
onclick Soporte Soporte Soporte Soporte Soporte

Más ejemplos

实例

Haga clic en el elemento <button> para mostrar la fecha y la hora actual:

<button onclick="getElementById('demo').innerHTML = Date()">¿Qué hora es?

Prueba por ti mismo

实例

单击 <p> 元素将其文本颜色更改为红色:

<p id="demo" onclick="myFunction()">Click me to change my text color.</p>
<script>
function myFunction() {
  document.getElementById("demo").style.color = "red";
}
</script>

Prueba por ti mismo

实例

关于如何通过单击来更改 <p> 元素颜色的另一个例子:

<p onclick="myFunction(this, 'red')">Click me to change my text color.</p>
<script>
function myFunction(elmnt,clr) {
  elmnt.style.color = clr;
}
</script>

Prueba por ti mismo

实例

单击按钮将一些文本从输入字段复制到另一个输入字段:

<button onclick="myFunction()">Copy Text</button>
<script>
function myFunction() {
  document.getElementById("field2").value = document.getElementById("field1").value;
}
</script>

Prueba por ti mismo

实例

把 "onclick" 事件分配给 window 对象:
window.onclick = myFunction;
// 如果用户在窗口中单击,则将 <body> 的背景颜色设置为黄色
function myFunction() {
  document.getElementsByTagName("BODY")[0].style.backgroundColor = "yellow";
}

Prueba por ti mismo

实例

使用 onclick 创建下拉按钮:

// 获取按钮,当用户点击时,执行 myFunction
document.getElementById("myBtn").onclick = function() {myFunction()};
/* myFunction 在添加和删除 show 类之间切换,用于隐藏和显示下拉内容 */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

Prueba por ti mismo

Páginas relacionadas

Tutoriales de JavaScript:Eventos de JavaScript

Manual de referencia del DOM HTML:Evento ondblclick

Manual de referencia del DOM HTML:Evento onmousedown

Manual de referencia del DOM HTML:Evento onmouseup