思想:对于上一级元素、父元素实现下级元素、子元素变色。仅需 :hover 及 css 选择器便可完成。下级元素对上级操作,现使用 JavaScript 中 onmouseover、onmouseout 事件
注:网页版右上方的悬浮框有目录索引
一、HTML 代码
<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 的结束标签前
<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>
四、效果图
Column 1 | Column 2 |
---|---|