点击事件 onclick

2-1 输入框事件

2-1-1 onfocus 获取焦点

2-1-2 onblur 失去焦点

2-1-3 onchange 输入框内容改变时触发

  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. app.onchange = function(){
  11. console.log("hello world");
  12. }
  13. </script>

2-2 鼠标事件

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

2-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>

2-3 键盘事件与keyCode属性

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

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

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

  1. <input type="text" id="input">
  2. var input = document.getElementById("input")
  3. input.onkeydown = function(event){
  4. /*event.key 获取键盘按下对应的键
  5. event.keyCode 获取按下的键的状态码*/
  6. console.log(event.key)
  7. console.log(event.keyCode);
  8. if(event.keyCode == 85){
  9. console.log("发大招");
  10. }
  11. }
  12. input.onkeypress = function(){
  13. console.log("press");
  14. }

2-4 窗口事件

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

2-4-2onscroll 窗口滚动时触发

2-4-3onload 页面在加载完毕之后才会触发

  1. window.onresize = function(){
  2. console.log("窗口大小改变了");
  3. }
  4. window.onscroll = function(){
  5. console.log(2);
  6. }
  7. <p id="p">hello world</p>
  8. window.onload = function(){
  9. var p = document.getElementById("p")
  10. p.onclick = function(){
  11. console.log("hello world");
  12. }
  13. }

2-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>