<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HTML事件(onclick、onmouseover、onmouseout、this)</title> <!-- <ele onclick="a";>//鼠標單機HTML中的元素ele后,執行代碼a; <ele onmouseover="a";>//鼠標經過HTML中的元素ele時,執行代碼a; <ele onmouseout="a";>//鼠標移出HTML中的元素ele后,執行代碼a; this:一)在包含事件的HTML元素內使用,代表該元素本身 <ele 事件="this.style.background='red'">;//this=ele 表示觸發事件時,將元素ele的背景顏色變成紅色 二)用於將包含事件的HTML元素作為實參傳給函數; <ele 事件="函數(this,"參數1","參數2")> 表示通過this將ele元素傳參給函數並與之綁定,同時可以設置參數1、參數2..參數n function 函數(a,參數1,參數2){ //這里的a=this=ele,可以隨便命名,表示將元素ele引入函數 a.style.color=參數1;//為元素a設置字體顏色,顏色值可以直接寫明(如:a.style.color="red"),也可以通過參數1將HTML中參數1的值傳遞過來 } tips: 1)參數this始終表示包含事件的元素ele, 2)HTML中this在函數參數的位置對應script中函數的參數位置(例:在HTML中<ele function(a,this);>;this是第二個參數,那么在script中function(x,y)第二個參數y就是this; 3)因為是在HTML中調用了script內的函數,所以,script中函數的參數最終值=HTML中元素ele內設置的參數值; --> <style> .a{ width: 100px; height: 40px; background: red; margin-top: 10px; border-radius: 10px/10px; } .b{ width: 100px; height: 40px; background: greenyellow; margin-top: 10px; border-radius: 10px/10px; } </style> </head> <body> <!-- 如下:單機按鈕彈出“我是誰”,移入鼠標時背景變為粉色,移出鼠標后背景變為透明 --> <input type="button" value="按鈕" onclick="alert('我是誰')" onmouseover="this.style.background='pink'" onmouseout="this.style.background='transparent'" /><!-- 單機按鈕后頁面彈出“我是誰” --> <!-- 如下:鼠標移入div時,執行函數fun1;移出div后,執行函數fun2;//this代表整個div元素,並和函數綁定,此時函數的兩個參數分別是x=this=div,y=background=blue; --> <div class="a" onmouseover="fun1(this,'blue')" onmouseout="fun2(this,'red')">a</div> <!-- 如下:鼠標移入div時,執行函數fun3;移出div后,執行函數fun4,//此時函數只有一個參數就是this=div --> <div class="b" onmouseover="fun3(this)" onmouseout="fun4(this)">b</div> <script> //div.a function fun1(x,y){ //參數x=this=div.a;參數y='blue'; x.style.background=y;//div.a{background: blue;}鼠標移入div.a時,div變為藍色 console.log(x); } function fun2(x,y){ //參數x=this=div.a;參數y='red'; x.style.background=y;//div.a{background: red;}鼠標移出div.a后,div變為紅色 console.log(x); } //div.b function fun3(Q){ //參數x=this=div.b; Q.style.background="grey";//div.b{background: grey;}鼠標移入div.b時,div變為灰色 console.log(Q); } function fun4(隨便){ //參數:隨便=this=div.b; 隨便.style.background="greenyellow";//div.b{background: greenyellow;}鼠標移出div.b后,div變成黃綠色 console.log(隨便); } </script> </body> </html>
