sự kiện onclick
Ví dụ
Gọi một hàm khi nhấn nút:
<button onclick="myFunction()">Click me</button>
Hãy tự mình thử »Thêm ví dụ dưới đây.
Sự miêu tả
Sự kiện onclick
xảy ra khi người dùng nhấp vào phần tử HTML .
Sự kiện chuột
Event | Occurs When |
---|---|
onclick | The user clicks on an element |
oncontextmenu | The user right-clicks on an element |
ondblclick | The user double-clicks on an element |
onmousedown | A mouse button is pressed over an element |
onmouseenter | The pointer is moved onto an element |
onmouseleave | The pointer is moved out of an element |
onmousemove | The pointer is moving over an element |
onmouseout | The mouse pointer moves out of an element |
onmouseover | The mouse pointer is moved over an element |
onmouseup | The mouse button is released over an element |
Xem thêm:
Hướng dẫn:
Cú pháp
Trong JavaScript, sử dụng phương thức addEventListener():
object .addEventListener("click", myScript );
Hãy tự mình thử »Chi tiết kỹ thuật
Bong bóng: | Đúng |
---|---|
Có thể hủy: | Đúng |
Loại sự kiện: | ChuộtSự kiện |
Được hỗ trợ Thẻ HTML: | Tất cả ngoại trừ: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> và <title> |
Thêm ví dụ
Bấm vào <button> để hiển thị ngày:
<button onclick="getElementById('demo').innerHTML = Date()">What is the time?</button>
Hãy tự mình thử »Nhấp vào phần tử <h3> để thay đổi màu văn bản:
<h3 id="demo" onclick="myFunction()">Click me to change my color.</h3>
<script>
function myFunction() {
document.getElementById("demo").style.color = "red";
}
</script>
Hãy tự mình thử »Một ví dụ khác về cách thay đổi màu của một phần tử:
<h3 onclick="myFunction(this, 'red')">Click me to change my color.</h3>
<script>
function myFunction(element, color) {
element.style.color = color;
}
</script>
Hãy tự mình thử »Bấm để sao chép văn bản từ trường nhập này sang trường nhập khác:
<button onclick="myFunction()">Copy Text</button>
function myFunction() {
document.getElementById("field2").value =
document.getElementById("field1").value;
}
</script>
Hãy tự mình thử »Cách gán sự kiện "onclick" cho đối tượng cửa sổ:
window.onclick = myFunction;
function myFunction() {
document.getElementsByTagName("BODY")[0].style.backgroundColor = "yellow";
}
Hãy tự mình thử »Sử dụng onclick để tạo danh sách thả xuống:
document.getElementById("myBtn").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
Hãy tự mình thử »Hỗ trợ trình duyệt
onclick
là tính năng DOM Cấp 2 (2001).
Nó được hỗ trợ đầy đủ trong tất cả các trình duyệt:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |