目录
前言
今日讲解JS新事件,它分为三种:鼠标事件,键盘事件,浏览器事件。
接下来一一为大家展示。
一、鼠标事件
1.单击事件(onclick)
在鼠标指针单击时触发
<!--html代码-->
<header id="head">我是头部,别点我</header>
//js代码
var head = document.getElementById('head')
head.onclick = function () {
console.log('我被单击了');
}
2、双击事件(ondblclick)
在鼠标光标双击时触发
<!--html代码-->
<header id="head">我是头部,别点我</header>
//js代码
var head = document.getElementById('head')
head.ondblclick = function () {
console.log('我被双击了');
}
3、移入事件(onmouseover)
在鼠标指针移动到元素上时触发
<!--html代码-->
<header id="head">我是头部</header>
//js代码
var head = document.getElementById('head')
head.onmouseover = function () {
console.log('移入了');
//加一点样式可以直观看出区别
this.style.height='200px'
}
4、移出事件(onmouseout)
在鼠标指针移出元素时触发
<!--html代码-->
<header id="head">我是头部</header>
//js代码
var head = document.getElementById('head')
head.onmouseout = function () {
console.log('移出了');
}
5、进入事件(onmouseenter)
在鼠标指针进入到元素上时触发
<!--html代码-->
<header id="head">我是头部</header>
//js代码
var head = document.getElementById('head')
head.onmouseenter = function () {
console.log('进入了');
}
6、离开事件(onmouseleave)
在鼠标指针离开元素后触发
<!--html代码-->
<header id="head">我是头部</header>
//js代码
var head = document.getElementById('head')
head.onmouseleave= function () {
console.log('离开了');
}
7、按下事件(onmousedown)
在鼠标单击按住不松手时触发
<!--html代码-->
<header id="head">我是头部</header>
//js代码
var head = document.getElementById('head')
head.onmousedown= function () {
console.log('按下');
}
8、抬起事件(onmouseup)
在鼠标单击按住后松手时触发
<!--html代码-->
<header id="head">我是头部</header>
//js代码
var head = document.getElementById('head')
head.onmouseup= function () {
console.log('抬起');
}
9、移动事件(onmousemove)
当鼠标指针的位置发生变化时触发
<!--html代码-->
<header id="head">我是头部</header>
//js代码
var head = document.getElementById('head')
head.onmousemove= function () {
console.log('移动了');
}
10、获取焦点(onfocus)
在鼠标光标获取输入框焦点时触发
<!--html代码-->
<input type="text" id="user">
//js代码
document.getElementById('user').onfocus = function () {
console.log('获取焦点');
}
11、失去焦点(onblur)
在鼠标光标失去焦点时触发
<!--html代码-->
<input type="text" id="user">
//js代码
document.getElementById('user').onblur = function () {
console.log('失去焦点');
}
二、键盘事件
1.按下事件(onkeydown)
键盘按下时触发
<!--html代码-->
<input type="text" id="user">
//js代码
document.getElementById('user').onkeydown = function () {
console.log('键盘已按下');
}
2.抬起事件(onkeyup)
键盘抬起时触发
<!--html代码-->
<input type="text" id="user">
//js代码
document.getElementById('user').onkeyup = function () {
console.log('键盘已抬起');
}
三、浏览器事件
1.加载完成事件(onload)
浏览器加载完成执行
//js代码
window.onload = function () {
console.log('加载完成!');
}
2.滚动事件(onscroll)
滚动浏览器滚动条时触发
//js代码
window.onscroll = function () {
console.log("滚动了!");
}
总结
以上就是今天的内容。