JS学习笔记–常用事件
在js中有非常多事件,此文章对常用的事件进行一些整理
测试用的html代码(统一在此代码测试)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box{
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
</html>
一、鼠标常用事件
onmouseover / onmouseout
mouseover: 当鼠标移动到某个元素上时触发
mouseout:当鼠标移除某个元素时触发
box.onmouseover = function () {
console.log('我是over')
}
box.onmouseout = function () {
console.log('我是out')
}
2. onmouseenter / onmouseleave
mouseenter:当鼠标进入某一个元素时触发
mouseleave:当鼠标移除时触发
box.onmouseenter = function () {
console.log('我是enter')
}
box.onmouseleave = function () {
console.log('我是leave')
}
这两组事件的区别
我们可以看见在上面案例onmouseenter
和onmouseover
执行的结果是一样的,但是在某些特定的场景下就能体现出它们的区别
JS代码不变 我们在box盒子中增加一个inner的盒子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box {
position: relative;
width: 100px;
height: 100px;
background: red;
}
#inner{
position: absolute;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
width: 50px;
height: 50px;
background: green;
}
</style>
</head>
<body>
<div id="box">
<div id="inner"></div>
</div>
</body>
</html>
我们看一下执行结果
3. onmousemove
mousemove:当鼠标在元素上移动触发
box.onmousemove = function(){
console.log('我是move')
}
4.onmousedown / onmouseup / onlick
mousedown:当鼠标在某个元素内按下时触发
onmouseup:当鼠标在某个元素内抬起时触发
onlick: 当鼠标单机时触发(一次按下一次抬起才算一次单机)扫描二维码关注公众号,回复: 11302287 查看本文章
box.onmousedown = function () {
console.log('我是down')
}
box.onclick = function(){
console.log('我是click')
}
box.onmouseup = function () {
console.log('我是up')
}
5.onmousewheel
mouselwheel:鼠标在某个元素内 滚轮滑动
二、键盘事件
onkeydown / onkeyup / onkeypress
keydown:当键盘按下时触发
keyup:当抬起时触发
keypress:紧接着keydown后面触发,但是只有按下字母才会触发
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box {
position: relative;
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
tabindex:设置元素是可以聚焦的(即可以获得焦点的)
contenteditable:设置div是否可编辑状态
<div id="box" tabindex="0" contenteditable="true"></div>
<script>
box.onkeydown = function () {
console.log('我是down')
}
box.onkeyup = function () {
console.log('我是up')
}
box.onkeypress = function () {
console.log('我是press')
}
</script>
</body>
</html>
三、表单事件
input / submit / change / reset
input:当表单发生改变的时候触发,(即时触发)
submit:当表单数据向服务器提交时触发
change:当表单发生改变且失去焦点时触发
reset:当表单重置(所有表单成员变回默认值)时触发
表单事件相对简单,请大家自行测试
四、移动端事件
ontouchstart / ontouchmove / ontouchend
touchstart:当手指放在手机屏幕上时触发
touchmove:当手指在手机屏幕上移动时触发
touchend:当手指离开手机时触发
box.ontouchstart = function () {
console.log('我是start')
}
box.ontouchmove = function () {
console.log('我是move')
}
box.ontouchend = function () {
console.log('我是end')
}