DOM中的事件

xiaoxiao2021-02-28  141

事件就是文档或浏览器窗口发生的一些特定的交互瞬间,事件的三要素 分别是:事件源(触发事件的元素)、事件名称(触发事件的名称)、事件处理函数(触发事件时调用的函数)。 在js中有很多事件,下面我们就来说一下常用的一些事件。

onclick()事件:点击事件,当鼠标点击元素的时候触发的事件,下面的代码做一个展示; <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #box{ width: 200px; height: 200px; background-color: aquamarine; } </style> </head> <body> <input type="button" id="btn" value="隐藏"> <br> <div id="box"> </div> </body> </html> <script> //获取对象 var oBtn=document.getElementById("btn"); var oBox=document.getElementById("box"); // 给隐藏按钮注册点击事件 oBtn.onclick=function () { oBox.style.display="none"; } </script>

2.onfocus()获取焦点事件

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" id="search" value="女神的新装" > </body> </html> <script> window.onload=function () { var Search = document.getElementById("search"); Search.onfocus=function () { this.value = ""; } } </script>

3.onblur()失去焦点事件

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" id="search" value="女神的新装" > </body> </html> <script> window.onload=function () { var Search = document.getElementById("search"); Search.onfocus=function () { this.value = ""; }; Search.onblur=function () { if(Search.value==""){ this.value = "女神的新装"; } } } </script>

4.onmouseover()当鼠标经过的时候触发 onmouseout()当鼠标离开的时候触 这两个事件通常会放在一起使用,因为当鼠标经过某个元素触发onmouseover()事件之后在鼠标移出之后还需要元素返回原本的样子

<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> .nodeSmall { width: 50px; height: 50px; background: url(images/bgs.png) no-repeat -159px -51px; position: fixed; right: 10px; top: 40%; } .pic { position: absolute;!important; top: 0; left: -150px; } .nodeSmall a { display: block; width: 50px; height: 50px; } .hide { display: none; } .show { display: block; } </style> </head> <body> <div class="nodeSmall" id="node_small"> <a href="#" id="link"></a> <div class="pic hide" id="er"> <img src="images/456.png" alt=""/> </div> </div> <script> //1. 找对象 var link=document.getElementById("link"); var er=document.getElementById("er"); //onmouseover:当鼠标经过的时候触发 //onmouseout:当鼠标离开的时候触 //2. 给a标签注册鼠标经过事件, 让二维码显示 link.onmouseover = function () { er.className="pic show" }; //3. 给a标签注册鼠标离开事件, 让二维码隐藏 link.onmouseout=function () { er.className="pic hide" } </script> </body> </html>

5.onload()会在页面或图像加载完成后立即发生。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" id="search" value="女神的新装" > </body> </html> <script> //调用window的onload方法,当文档加载完成之后才会执行内部的代码,不会因为代码的读取顺序而导致找不到对象 window.onload=function () { var Search = document.getElementById("search"); Search.onfocus=function () { this.value = ""; } } </script>
转载请注明原文地址: https://www.6miu.com/read-17965.html

最新回复(0)