为了让我们更好的和浏览器交互;
事件一般是定义在元素的节点上的,所以我们一般称之为给元素节点绑定一个事件。
定义事件的三种方式
(1) addEventListener方法
注:事件使用addEventListener方式定义的时候要去掉on
<div style="width: 100px;height: 100px;background-color: pink;"></div><script>var btn=document.querySelector('div');//方法btn.addEventListener('click',function(){btn.setAttribute('style',"width:200px;height: 200px;background-color: salmon;")})</script>
(2) onclick属性
<div style="width: 100px;height: 100px;background-color: pink;"></div><script>var btn=document.querySelector('div');//方法btn.onclick = function(){alert("哈哈哈")}</script>//或者<div onclick="f(123)" style="width: 100px;height: 100px;background-color: pink;"></div><script>var btn=document.querySelector('div');function f(num){alert(num)}</script>
事件分类
(1) 鼠标事件
1.1 onclick
点击鼠标的时候触发
1.2 ondblclick
双击鼠标的时候触发
1.3 onmouseover
鼠标悬停在元素上的时候触发
hello world
1.4 onmouseout
鼠标移开的时候触发
p.onmouseout=function(){
this.style.backgroundColor="green"}
(2) 键盘事件
2-1、onkeydown用户按下一个键盘按键时发生
<input type="text" id="in"><script>/** event.key 获取键盘按的值* event.keyCode 回车:13 R:82*/var t = document.getElementById('in');t.addEventListener('keydown',function(){console.log(event.keyCode)if(event.keyCode=='enter'){ //回车console.log("放下")}})</script>
2-2、onkeyup在键盘按键松开时发生
t.addEventListener('keyup',function(){console.log('松开')})
2-3、onkeypress在键盘按键按下并释放一个键时发生
input.onkeypress = function(){console.log("press")}
(3) 表单事件
3-1、onfocus获取焦点
3-2、onblur遗失焦点
<body><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></body>
3-3、onchange
当输入框的内容发生改变的时候,触发
<body><input type="text" id="input"><script>// 当输入框的内容发生改变的时候,触发var input = document.getElementById("input");input.onchange = function(){console.log("hello world")}</script></body>
3-4、onsubmit表单中的确认按钮被点击时发生
<body><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><script></script></body>
(4) 窗口
2-1、onresize
窗口大小改变的时候,会触发
<body><input type="text" id="input"><script>// 当输入框的内容发生改变的时候,触发var input = document.getElementById("input");input.onchange = function(){console.log("hello world")}// onresize窗口大小改变的时候,会触发window.onresize = function(){console.log(1)}// 窗口滚动的时候会触发window.onscroll = function(){console.log(2)}</script></body>
2-2、onscroll
窗口滚动的时候会触发
window.onscroll = function(){console.log(2)
2-3、onload
页面在加载完毕之后才会触发
<p id="p">hello world</p>window.onload = function(){var p = document.getElementById("p")p.onclick = function(){console.log("hello world");}}
