案例:点击按钮弹框
<body> <input type="button" value="按钮" id="btn"> <script> document.getElementById("btn").onclick = function () { alert("点击了"); }; </script> </body>
案例:鼠标进入红色,离开蓝色(放上去就可以,不用点击)
<head> <meta charset="UTF-8"> <title>Title</title> <style> div { width: 200px; height: 200px; background-color: aqua; } </style> </head> <body> <div id="dv"></div> <script> document.getElementById("dv").onmouseover = function () { document.getElementById("dv").style.backgroundColor = "red"; }; document.getElementById("dv").onmouseout = function () { document.getElementById("dv").style.backgroundColor = ""; }; </script> </body>
案例:文本框
<body> <input type="text" value="请输入内容" id="te"> <script> document.getElementById("te").onfocus = function () { document.getElementById("te").value = ""; }; document.getElementById("te").onblur = function () { document.getElementById("te").value = "请输入内容"; }; </script> </body>
鼠标移动的时候就会触发
案例:div 跟着鼠标移动
<head> <meta charset="UTF-8"> <title>Title</title> <style> div { width: 50px; height: 50px; background-color: pink; position: absolute; } </style> </head> <body> <div id="dv"></div> <script> 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"; }; </script> </body>
当拖动滚动条的时候就会触发
<head> <meta charset="UTF-8"> <title>Title</title> <style> div { width: 100px; height: 100px; background-color: pink; overflow: auto; } </style> </head> <body> <div id="dv"> 码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙码仙 </div> <script> document.getElementById("dv").onscroll = function () { console.log("滚动条被拖动了"); }; </script> </body>
当键盘按下或者抬起任意按键的时候触发
<body> <input type="text" id="txt"> <script> document.getElementById("txt").onkeydown = function () { console.log("键盘按下了"); }; document.getElementById("txt").onkeyup = function () { console.log("键盘抬起了"); }; </script> </body>
<script> //页面的任何的位置.按下键盘,获取按键的值 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; } }; </script>
当鼠标左键或右键按下或者抬起的时候触发
按下或抬起滚动轮也会触发,滑动滚动轮不能触发
如果鼠标比较高级,有其他按键的情况下,按下或抬起也会触发
<head> <meta charset="UTF-8"> <title>Title</title> <style> div { width: 50px; height: 50px; background-color: pink; } </style> </head> <body> <div id="dv"></div> <script> document.getElementById("dv").onmousedown = function () { console.log("鼠标按下了"); }; document.getElementById("dv").onmouseup = function () { console.log("鼠标抬起了"); }; </script> </body>
本篇博客来自于传智播客视频教程的总结以及笔记的整理,仅供学习交流,切勿用于商业用途
到此这篇关于JavaScript中常见的事件用法小结的文章就介绍到这了,更多相关js事件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章: