onfocus,onblur
onfocus 事件在对象获得焦点时发生。 onblur 事件会在对象失去焦点时发生。
<input id="app" type="text"><script>/*onfocus 获取焦点onblur 遗失焦点*/var app = document.getElementById("app");app.onfocus = function(){this.style.backgroundColor = "red"}app.onblur = function(){this.style.backgroundColor = "yellow"}</script>
mouseover,mouseout
mouseover 鼠标悬停在元素上的时候触发 mouseout 鼠标移开的时候触发
<p id="p">hello world</p><script>var p = document.getElementById("p");p.onmouseover = function(){this.style.background = "red"}p.onmouseout = function(){this.style.background = "green"}</script>
window.onload 页面加载完后触发
<p id="p">hello world</p>
/* 页面加载完毕之后才会触发 */window.onload = function () {var p = document.getElementById("p");p.onclick = function () {console.log("hello world")}}
onchange,onresize,onscroll
onchange:当输入框的内容发生改变的时候,触发 onresize:窗口大小改变的时候,会触发 onscroll:窗口滚动的时候会触发
<style>body{height:2000px;}</style><body><input type="text" id="input"><script>var input = document.getElementById("input");input.onchange = function(){console.log("hello world")}window.onresize = function(){console.log(1)}window.onscroll = function(){console.log(2)}</script></body>
onsubmit
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>
onkeydown () ,onkeyup(),onkeypress(),key,keyCode
keyCode对照表 key 事件在按下按键时返回按键的标识符。 keyCode(注意大写C) 属性返回onkeypress事件触发的键的值的字符代码,或者 onkeydown 或 onkeyup 事件的键的代码。 onkeypress 事件会在键盘按键被按下并释放一个键时发生。 onkeydown 事件会在用户按下一个键盘按键时发生。 onkeyup 事件会在键盘按键被松开时发生。
<input type="text" id = "input"><script>/*event.key 获取按下键盘键对应的值event.keyCode 13回车82 R*/var input = document.getElementById("input");input.onkeydown = function(event){console.log(event.keyCode)if(event.keyCode == 82){console.log("放下")}}input.onkeypress = function(){console.log("press")}input.onkeyup = function(){console.log("放开")}</script>
回车添加值至数组
<input type="" id="input"><script>var arr = [];var input = document.getElementById("input");input.onkeyup= function(event){if(event.keyCode == 13){arr.push(this.value)console.log(arr)}}</script>
