javascript實(shí)現(xiàn)鼠標(biāo)懸停變色的方法:1、元素綁定onmouseover事件,并設(shè)置事件處理函數(shù);2、在事件處理函數(shù)中,使用“元素對(duì)象.style.顏色屬性名="顏色值";”語句設(shè)置當(dāng)觸發(fā)懸停事件時(shí),元素顏色改變效果。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
思想:對(duì)于上一級(jí)元素、父元素實(shí)現(xiàn)下級(jí)元素、子元素變色。僅需 :hover 及 css 選擇器便可完成。下級(jí)元素對(duì)上級(jí)操作,現(xiàn)使用 JavaScript 中 onmouseover、onmouseout 事件
-
onmouseover 事件會(huì)在鼠標(biāo)指針移動(dòng)到指定的元素上時(shí)發(fā)生。
-
onmouseout 事件會(huì)在鼠標(biāo)指針移出指定的對(duì)象時(shí)發(fā)生。
一、HTML 代碼
<body> <div id="A"> <div id="B"> 鼠標(biāo)移動(dòng)到 A div 時(shí),我要變色 </div> </div> <hr /> <div id="AB"> <div id="a"> 一號(hào) div </div> <div id="b"> 二號(hào) div </div> </div> </body>
二、JavaScript 代碼
??注:建議寫在 body 的結(jié)束標(biāo)簽前
<script type="text/javascript"> document.getElementById("b").onmouseover=function(){ document.getElementById("a").style.backgroundColor="green"; } document.getElementById("b").onmouseout=function(){ document.getElementById("a").style.backgroundColor="red"; } </script>
三、CSS 代碼
<style type="text/css"> #A{ height: 400px; width: 400px; background-color: red; } #B{ height: 300px; width: 300px; background-color: green; display: none; } #A:hover #B{ display: block; } #a{ height: 300px; width: 300px; background-color: red; } #b{ margin-left: 50px; height: 300px; width: 300px; background-color: red; } #a:hover+#b { background-color: green; } </style>
四、效果圖
【