下面的JSFiddle显示当我在DIV A上悬停时,DIV B会改变颜色,但我需要完全相反的情况:在DIV B上悬停,让DIV A改变颜色。
http://jsfiddle.net/u7tYE/
<div id="a">Div A</div>
<div id="b">Div B</div>
#a:hover + #b {
background: #ccc
}我不能重新排列原始的html元素,它们需要保持不变。
这是可能的CSS,还是只有Javascript?
发布于 2016-02-28 08:04:28
您需要一点jQuery,因为您不能改变以前在CSS中使用悬停样式的兄弟姐妹:
$('#b').hover(
function(){
$('#a').css({'background':'#ccc'});
},
function(){
$('#a').css({'background':'initial'});
}
);//#a:hover + #b {
// background: #ccc
//}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="a">Div A</div>
<div id="b">Div B</div>
编辑: w/ vanilla javascript:
var a = document.getElementById('a');
var b = document.getElementById('b');
b.onmouseover = function(e) {
a.style.background = '#CCC';
}
b.onmouseout = function(e) {
a.style.background = 'initial';
}//#a:hover + #b {
// background: #ccc
//}<div id="a">Div A</div>
<div id="b">Div B</div>
发布于 2016-02-28 08:11:09
也许你需要的是普通的兄弟姐妹选择:它选择任何兄弟姐妹,而不仅仅是下一个。
#b:hover ~ #a { background: ...; }发布于 2016-02-28 08:13:15
使用css有点困难,但是尝试一下
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
</head>
<style type="text/css">
body{
margin: 0;
padding: 0;
}
div#a{
width: 100px;
height: 100px;
background-color: orange;
margin: 10px;
position: absolute;
top:110px;
}
div#b{
width: 100px;
height: 100px;
background-color: gray;
margin: 10px;
position: absolute;
}
div#a:hover +div#b{
background-color: black;
}
</style>
<div id="a"></div>
<div id="b"></div>
</body>
</html>
否则,最简单的方法是使用jquery.this完成it.try this.hope的完整代码,这将对您有所帮助。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<style type="text/css">
body{
margin: 0;
padding: 0;
}
div#a{
width: 100px;
height: 100px;
background-color: orange;
margin: 10px;
}
div#b{
width: 100px;
height: 100px;
background-color: gray;
margin: 10px;
}
</style>
<div id="a"></div>
<div id="b"></div>
<script type="text/javascript">
$("div#b").mouseenter(function(){
$("div#a").css({"background-color":"black"});
});
$("div#b").mouseleave(function(){
$("div#a").css({"background-color":"orange"});
});
</script>
</body>
</html>
https://stackoverflow.com/questions/35680033
复制相似问题