JS-事件处理

1、一个简单的单击事件:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
     
</head>
<body>
   <button onclick="demo()">按钮</button>
   <script>
      function demo(){
          alert("hello");
      }
   </script>
</body>
</html>


2、鼠标事件 onmouseout,onmouseover

    当鼠标经过会显示“hello”,当鼠标移出会显示“world”

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>事件</title>
 6      <link rel="stylesheet" href="style.css" type="text/css">
 7 </head>
 8 <body>
 9    <div class="div" onmouseout="onOut(this)" onmouseover="onOver(this)"></div>
10    <script>
11       function onOver(ooj){
12           ooj.innerHTML = "hello";
13       }
14       function onOut(ooj){
15           ooj.innerHTML = "world";
16       }
17    </script>
18 </body>
19 </html>

css代码:

.div{
    100px;
    height:100px;
    background-color: aqua;
}

3、onchange,当内容改变了,弹出提示框(hello,内容改变了)

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>事件</title>
 6      <link rel="stylesheet" href="style.css" type="text/css">
 7 </head>
 8 <body>
 9    
10    <form>
11       <input type="text" onchange="changeDemo(this)">
12    </form>
13    <script>
14      function changeDemo(bg){
15          alert("Hello 内容改变了");
16      }
17    </script>
18 </body>
19 </html>

或者这样写,达到的效果是一样的

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>事件</title>
 6      <link rel="stylesheet" href="style.css" type="text/css">
 7 </head>
 8 <body>
 9    
10    <form>
11       <input type="text" onchange="alert('hello 内容改变了')">
12    </form>
13    
14 </body>
15 </html>

4、onselect,当在文本框中写点内容,然后选中这些内容时,背景颜色会变成红色

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>事件</title>
 6      <link rel="stylesheet" href="style.css" type="text/css">
 7 </head>
 8 <body>
 9    
10    <form>
11       <input type="text" onselect="demo(this)">
12    </form>
13    
14    <script>
15      function demo(bg){
16          bg.style.background="red";
17      }
18    </script>
19    
20 </body>
21 </html>

5、onfocus,当光标点击之后,背景变成蓝色

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>事件</title>
 6      <link rel="stylesheet" href="style.css" type="text/css">
 7 </head>
 8 <body>
 9    
10    <form>
11       <input type="text" onfocus="demo(this)">
12    </form>
13    
14    <script>
15      function demo(bg){
16          bg.style.background="blue";
17      }
18    </script>
19    
20 </body>
21 </html>

6、onload,当网页加载完毕后弹出:网页加载完毕

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>事件</title>
 6      <link rel="stylesheet" href="style.css" type="text/css">
 7 </head>
 8 <body onload="demo()">
 9    <script>
10      function demo(bg){
11          alert("网页内容加载完毕");
12      }
13    </script>
14    
15 </body>
16 </html>
原文地址:https://www.cnblogs.com/UniqueColor/p/5750715.html