在 CSS 悬停事件中,我可以更改上面 div 的样式吗?

On a CSS hover event, can I change the above div's styling?

当我将鼠标悬停在 DIV A 上时,下面的 JSFiddle 显示 DIV B 改变颜色。但我需要完全相反的方法:将鼠标悬停在 DIV B 上并让 DIV 变色

http://jsfiddle.net/u7tYE/

<div id="a">Div A</div>
<div id="b">Div B</div>

#a:hover + #b {
    background: #ccc
}

我无法重新排列原始 html 元素,它们需要保持不变。

CSS 或仅 Javascript 可行吗?

您需要一点 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>

编辑:带原版 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>

也许您需要的是通用同级选择器:它可以选择任何同级,而不仅仅是下一个。

#b:hover ~ #a { background: ...; }

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>

这可以在 javascript

中完成
// mouse is over div b
document.getElementById("b").onmouseover = function(){
    document.getElementById("a").style.background = "#ccc"
}
// mouse leaves div b
document.getElementById("b").onmouseout = function(){
    document.getElementById("a").style.background = "intial"
}

您可以使用父元素来控制悬停样式,如下所示:

<div class="parent">
  <div id="a">Div A</div>
  <div id="b">Div B</div>
</div>

.parent:hover div {
  background: #ccc;
}
.parent div:hover,
.parent div:hover ~ div {
  background: none;
} 

http://jsfiddle.net/qemmhpem/1/