点击事件 onclick
2-1 输入框事件
2-1-1 onfocus 获取焦点
2-1-2 onblur 失去焦点
2-1-3 onchange 输入框内容改变时触发
<input id="app" type="text">
<script>
var app = document.getElementById("app")
app.onfocus = function(){
this.style.backgroundColor="red"
}
app.onblur = function(){
this.style.backgroundColor = "yellow"
}
app.onchange = function(){
console.log("hello world");
}
</script>
2-2 鼠标事件
2-2-1onmouseover 鼠标悬停在元素上时触发
2-2-2onmouseout 鼠标移开时触发
<p id="p">hello world</p>
<script>
var p = document.getElementById("p")
p.onmouseover = function(){
p.style.background = "red"
}
p.onmouseout = function(){
p.style.background = "green"
}
</script>
2-3 键盘事件与keyCode属性
2-3-1onkeydown 用户按下一个键盘按键时发生
2-3-2onkeypress 在键盘按键按下并释放一个键时发生
2-3-3onkeyup 在键盘按键松开时发生
<input type="text" id="input">
var input = document.getElementById("input")
input.onkeydown = function(event){
/*event.key 获取键盘按下对应的键
event.keyCode 获取按下的键的状态码*/
console.log(event.key)
console.log(event.keyCode);
if(event.keyCode == 85){
console.log("发大招");
}
}
input.onkeypress = function(){
console.log("press");
}
2-4 窗口事件
2-4-1onresize 窗口大小改变的时候触发
2-4-2onscroll 窗口滚动时触发
2-4-3onload 页面在加载完毕之后才会触发
window.onresize = function(){
console.log("窗口大小改变了");
}
window.onscroll = function(){
console.log(2);
}
<p id="p">hello world</p>
window.onload = function(){
var p = document.getElementById("p")
p.onclick = function(){
console.log("hello world");
}
}
2-5 表单事件
onsubmit 事件在表单提交时触发
<form id="form" onsubmit="alert(1)">
<p>
用户名:<input type="text" name="user">
</p>
<p>
密码:<input type="password" name="pwd">
</p>
<input type="submit" id="input">
</form>