一.onclick() 鼠标左键单击事件
案例:点击按钮弹框
1 2 3 | document.getElementById( "btn" ).onclick = function () { alert( "点击了" ); }; |
二.onmouseover 鼠标进入事件与onmouseout鼠标离开事件
案例:鼠标进入红色,离开蓝色(放上去就可以,不用点击)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <title>Title</title> div { width: 200px; height: 200px; background-color: aqua; } <div id= "dv" ></div> document.getElementById( "dv" ).onmouseover = function () { document.getElementById( "dv" ).style.backgroundColor = "red" ; }; document.getElementById( "dv" ).onmouseout = function () { document.getElementById( "dv" ).style.backgroundColor = "" ; }; |
三.onfocus 获取焦点事件与onblur 失去焦点事件
案例:文本框
1 2 3 4 5 6 | document.getElementById( "te" ).onfocus = function () { document.getElementById( "te" ).value = "" ; }; document.getElementById( "te" ).onblur = function () { document.getElementById( "te" ).value = "请输入内容" ; }; |
四.onmousemove 鼠标移动事件
鼠标移动的时候就会触发
案例:div 跟着鼠标移动
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <title>Title</title> div { width: 50px; height: 50px; background-color: pink; position: absolute; } <div id= "dv" ></div> document.onmousemove = function (e) { //鼠标相对于页面的可视区域的横坐标 var x = e.clientX; //鼠标相对于页面的可视区域的纵坐标 var y = e.clientY; //div对象 var dvobj = document.getElementById( "dv" ); //设置div的横坐标 dvobj.style.left = x + "px" ; //设置div的纵坐标 dvobj.style.top = y + "px" ; }; |
五.onscroll 滚动条滚动事件
当拖动滚动条的时候就会触发
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <title>Title</title> div { width: 100px; height: 100px; background-color: pink; overflow: auto; } <div id= "dv" > 码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙 </div> document.getElementById( "dv" ).onscroll = function () { console.log( "滚动条被拖动了" ); }; |
六. onkeydown / onkeyup 键盘按下/抬起事件
当键盘按下或者抬起任意按键的时候触发
1 2 3 4 5 6 | document.getElementById( "txt" ).onkeydown = function () { console.log( "键盘按下了" ); }; document.getElementById( "txt" ).onkeyup = function () { console.log( "键盘抬起了" ); }; |
七.keyCode 获取按下的是哪个按键
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //页面的任何的位置.按下键盘,获取按键的值 document.onkeydown = function (e) { //console.log(e.keyCode);//事件参数对象 switch (e.keyCode) { case 81: console.log( "您按下的是Q" ); break ; case 87: console.log( "您按下的是W" ); break ; case 69: console.log( "您按下的是E" ); break ; case 82: console.log( "您按下的是R" ); break ; } }; |
八. onmousedown / onmouseup 鼠标按下/抬起事件
当鼠标左键或右键按下或者抬起的时候触发
按下或抬起滚动轮也会触发,滑动滚动轮不能触发
如果鼠标比较高级,有其他按键的情况下,按下或抬起也会触发
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <title>Title</title> div { width: 50px; height: 50px; background-color: pink; } <div id= "dv" ></div> document.getElementById( "dv" ).onmousedown = function () { console.log( "鼠标按下了" ); }; document.getElementById( "dv" ).onmouseup = function () { console.log( "鼠标抬起了" ); }; |
本篇博客来自于传智播客视频教程的总结以及笔记的整理,仅供学习交流,切勿用于商业用途
到此这篇关于JavaScript中常见的事件用法小结的文章就介绍到这了,更多相关js事件内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!