onclick是一个事件,当事件被触发时就会执行处理,onclick是一个处理鼠标点击的事件。本篇文章就给大家分享关于JavaScript中onclick事件的用法。我们首先来看一下onclick事件的语法以下是如何使用onclick事件编写。使用document.getElementById()在文档中指定id元素,并使用function(){}处理单击该元素时发生的事件。
document.getElementById("button").onclick = function() {
// 设置在此处单击#button时要发生的事件
};
document.getElementById("button").onclick = function() {
// 设置在此处单击#button时要发生的事件
};我们来看具体的示例以下是使用onclick事件的示例。单击按钮时更改文字HTML代码

点击

CSS代码
#text-button {
display: block;
cursor: pointer;
width: 160px;
text-align: center;
border: 1px solid #232323;
}
#text-button {
display: block;
cursor: pointer;
width: 160px;
text-align: center;
border: 1px solid #232323;
}JavaScript代码
document.getElementById("text-button").onclick = function() {
document.getElementById("text").innerHTML = "我点击了!";
};
document.getElementById("text-button").onclick = function() {
document.getElementById("text").innerHTML = "我点击了!";
};浏览器上显示结果如下当点击这个方框后,就会显示如下效果:方框中文字改变了点击方框时,方框背景颜色改变HTML代码
CSS代码
#square-button {
width: 80px;
height: 80px;
background: #232323;
}
#square-button.blue {
background: #21759b;
}
JavaScript代码

document.getElementById("square-button").onclick = function() {
this.classList.toggle("blue");
};
#square-button {
width: 80px;
height: 80px;
background: #232323;
}
#square-button.blue {
background: #21759b;
}
JavaScript代码

document.getElementById("square-button").onclick = function() {
this.classList.toggle("blue");
};浏览器上显示如下效果:是一个黑色的方框当点击这个方框后,颜色就会改变,显示效果如下显示表单中输入的内容HTML代码

你叫什么名字?





你叫什么名字?




CSS代码
:focus {
outline: 1px solid #666;
}
input[type="text"] {
margin: 0 0 15px;
padding: 8px 10px;
border: 1px solid #d0d1d3;
}
button {
padding: 8px 15px;
background: #979380;
color: #fff;
border: none;
}
:focus {
outline: 1px solid #666;
}
input[type="text"] {
margin: 0 0 15px;
padding: 8px 10px;
border: 1px solid #d0d1d3;
}
button {
padding: 8px 15px;
background: #979380;
color: #fff;
border: none;
}JavaScript代码
document.getElementById("form-button").onclick = function() {
document.getElementById("form-text").innerHTML = "你好 " + document.getElementById("name").value + " 同学!";
}
document.getElementById("form-button").onclick = function() {
document.getElementById("form-text").innerHTML = "你好 " + document.getElementById("name").value + " 同学!";
}浏览器上显示效果如下当你在文本框中输入一个名字,比如张三,然后点击输入将会显示如下效果以上就是本文的全部内容,希望对大家的学习有所帮助。