当我悬停一个元素(一个用css制作的盒子)时,我希望身体的background color
从一种颜色变为另一种颜色,例如从白色变为红色。问题是这应该只使用css而不是javascript来完成。如果必须使用javascript,那么在鼠标移出时颜色应该会变回前一个颜色。
--------------- EDIT ---------------
其实我在尝试这个:
body{backgroung: #000;}
#div{some properties}
body #div:hover{background: #fff;}
答案 0 :(得分:11)
纯CSS实验:
http://jsfiddle.net/Tymek/yrKRX/
<强> HTML 强>
<div id="trigger"></div>
<div id="bg"></div>
<强> CSS 强>
body {
height: 100%;
}
#bg {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
widht: 100%;
height: 100%;
z-index: 1;
background: #EEE;
}
#trigger {
position: absolute;
width: 200px;
height: 136px;
top: 50%;
left: 50%;
margin: -68px 0 0 -100px;
background: #333;
z-index: 2;
}
/* KEY */
#trigger:hover ~ #bg {
background: #EE0;
}
答案 1 :(得分:1)
请像这样使用
<html>
<body>
<style type="text/css">
.top{
background:red;
}
.top2{
background:white;
}
</style>
<div class="top" onmouseover="this.className='top2'"
onmouseout="this.className='top'">Here</div>
</body>
</html>
答案 2 :(得分:1)
使用:hover
选择器。
除非你做的事情非常不同,否则看起来很简单。
检查以下示例以供参考:
.classname {
background-color:white;
}
.classname:hover {
background-color:red;
}
答案 3 :(得分:-1)
<强> Working fiddle 强>
您的代码中有很多拼写错误,例如将background
拼写为backgroung
并将div
视为ID(#div
)。
CSS (对拼写错误有解释)
body{background: #000;} /*backgroung (mis-spelled)*/
div{width:100px; /*#div (treated as ID)*/
height:100px;
border:1px solid black;}
要将鼠标悬停在父标记上,您必须强制使用javascript或jQuery。您可能会怀疑为什么没有css属性来选择父标记,如果是,那么您可以通过这个 interesting link 。为了避免在大多数情况下使用父选择器概念,我们可以使用CSS中的定位来逃避(查看Tymek的解决方案)。
<强>的jQuery 强>
$(document).ready(function(){
$("div").hover(function(){
$(this).parent(this).css('background-color','red');
});
$("div").mouseleave(function(){
$(this).parent(this).css('background-color','white');
});
});
假设您不熟悉jQuery,请在HTML的head
标记中提供一个链接,如下所示,以使上述功能正常工作。
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>