1 onfocus

1-1 onfocus 获取焦点

1-2 onblur 失去焦点

  1. <input id="app" type="text">
  2. <script>
  3. var app = document.getElementById("app")
  4. app.onfocus = function(){
  5. this.style.backgroundColor="red"
  6. }
  7. app.onblur = function(){
  8. this.style.backgroundColor = "yellow"
  9. }
  10. </script>

2 onmouse

2-1onmouseover 鼠标悬停在元素上时触发

2-2onmouseout 鼠标移开时触发

  1. <p id="p">hello world</p>
  2. <script>
  3. var p = document.getElementById("p")
  4. p.onmouseover = function(){
  5. p.style.background = "red"
  6. }
  7. p.onmouseout = function(){
  8. p.style.background = "green"
  9. }
  10. </script>

3.window相关事件

3-1 onload

window.onload 页面在加载完毕之后才会触发

  1. <p id="p">hello world</p>
  1. window.onload = function(){
  2. var p = document.getElementById("p")
  3. p.onclick = function(){
  4. console.log("hello world");
  5. }
  6. }

3-2 onresize 窗口大小改变的时候触发

  1. window.onresize = function(){
  2. console.log("窗口大小改变了");
  3. }

3-3 onscroll 窗口滚动时触发

  1. window.onscroll = function(){
  2. console.log(2);
  3. }

4 onchange

onchange 输入框内容改变时触发

  1. var input = document.getElementById("input")
  2. input.onchange = function(){
  3. console.log("hello world");
  4. }

5 onsubmit 事件在表单提交时触发

  1. <form id="form" onsubmit="alert(1)">
  2. <p>
  3. 用户名:<input type="text" name="user">
  4. </p>
  5. <p>
  6. 密码:<input type="password" name="pwd">
  7. </p>
  8. <input type="submit" id="input">
  9. </form>

6 键盘事件与KeyCode属性

event.key 获取键盘按下对应的键
event.keyCode 获取按下的键的状态码

6-1 onkeydown 用户按下一个键盘按键时发生

  1. <input type="text" id="input">
  2. var input = document.getElementById("input")
  3. input.onkeydown = function(event){
  4. console.log(event.key)
  5. console.log(event.keyCode);
  6. if(event.keyCode == 85){
  7. console.log("发大招");
  8. }
  9. }

6-2 onkeypress 在键盘按键按下并释放一个键时发生

  1. input.onkeypress = function(){
  2. console.log("press");
  3. }

6-3 onkeyup 在键盘按键松开时发生

  1. input.onkeyup = function(){
  2. console.log("up");
  3. }

6-4 获取输入框的值 element.value

  1. <input type="text" id="input" >
  2. <!-- element.value -->
  3. <script>
  4. var input =document.getElementById("input")
  5. input.onkeyup = function(event){
  6. if(event.keyCode == 13){
  7. console.log(this.value)
  8. }
  9. }
  10. </script>

7 内联事件

  1. <button id="btn" data-aid="123456" onclick="go(event)">
  2. btn
  3. </button>
  1. /* 内联事件
  2. 定义 data-aid="123456"
  3. 获取自定义属性值 event.target.dataset.aid
  4. */
  5. function go(event){
  6. console.log("hello world");
  7. console.log(event.target.dataset.aid);
  8. }

实例demo

  1. <p>还可以输入<em id="em" style="color:red">0</em>/30</p>
  2. <textarea id="txt" cols="30" rows="10"></textarea>
  3. <script>
  4. var txt = document.getElementById("txt")
  5. var em = document.getElementById("em")
  6. txt.onkeydown = function(){
  7. var length = this.value.length;
  8. if(length<=30){
  9. em.innerHTML = this.value.length;
  10. }else{
  11. alert("最多只能输入30个字符")
  12. }
  13. }
  14. </script>