javascript实现鼠标悬停变色的方法:1、元素绑定onmouseover事件,并设置事件处理函数;2、在事件处理函数中,使用“元素对象.style.颜色属性名="颜色值";”语句设置当触发悬停事件时,元素颜色改变效果。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
思想:对于上一级元素、父元素实现下级元素、子元素变色。仅需 :hover 及 css 选择器便可完成。下级元素对上级操作,现使用 JavaScript 中 onmouseover、onmouseout 事件
一、HTML 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <body>
<div id= "A" >
<div id= "B" >
鼠标移动到 A div 时,我要变色
</div>
</div>
<hr />
<div id= "AB" >
<div id= "a" >
一号 div
</div>
<div id= "b" >
二号 div
</div>
</div>
</body>
|
登录后复制
二、JavaScript 代码
注:建议写在 body 的结束标签前
1 2 3 4 5 6 7 8 | <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 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <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>
|
登录后复制
四、效果图


【相关推荐:javascript学习教程】
以上是javascript怎么实现鼠标悬停变色效果的详细内容。更多信息请关注PHP中文网其他相关文章!