1 onfocus
1-1 onfocus 获取焦点
1-2 onblur 失去焦点
<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"
}
</script>
2 onmouse
2-1onmouseover 鼠标悬停在元素上时触发
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>
3.window相关事件
3-1 onload
**window.onload 页面在加载完毕之后才会触发**
<p id="p">hello world</p>
window.onload = function(){
var p = document.getElementById("p")
p.onclick = function(){
console.log("hello world");
}
}
3-2 onresize 窗口大小改变的时候触发
window.onresize = function(){
console.log("窗口大小改变了");
}
3-3 onscroll 窗口滚动时触发
window.onscroll = function(){
console.log(2);
}
4 onchange
onchange 输入框内容改变时触发
var input = document.getElementById("input")
input.onchange = function(){
console.log("hello world");
}
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>
6 键盘事件与KeyCode属性
event.key 获取键盘按下对应的键
event.keyCode 获取按下的键的状态码
6-1 onkeydown 用户按下一个键盘按键时发生
<input type="text" id="input">
var input = document.getElementById("input")
input.onkeydown = function(event){
console.log(event.key)
console.log(event.keyCode);
if(event.keyCode == 85){
console.log("发大招");
}
}
6-2 onkeypress 在键盘按键按下并释放一个键时发生
input.onkeypress = function(){
console.log("press");
}
6-3 onkeyup 在键盘按键松开时发生
input.onkeyup = function(){
console.log("up");
}
6-4 获取输入框的值 element.value
<input type="text" id="input" >
<!-- element.value -->
<script>
var input =document.getElementById("input")
input.onkeyup = function(event){
if(event.keyCode == 13){
console.log(this.value)
}
}
</script>
7 内联事件
<button id="btn" data-aid="123456" onclick="go(event)">
btn
</button>
/* 内联事件
定义 data-aid="123456"
获取自定义属性值 event.target.dataset.aid
*/
function go(event){
console.log("hello world");
console.log(event.target.dataset.aid);
}
实例demo
<p>还可以输入<em id="em" style="color:red">0</em>/30</p>
<textarea id="txt" cols="30" rows="10"></textarea>
<script>
var txt = document.getElementById("txt")
var em = document.getElementById("em")
txt.onkeydown = function(){
var length = this.value.length;
if(length<=30){
em.innerHTML = this.value.length;
}else{
alert("最多只能输入30个字符")
}
}
</script>