CSS:过渡元素不会影响其他元素

时间:2013-11-27 11:16:45

标签: html css css-transitions

我想要做这种过渡效果,但它只适用于第一个div,周一旨在影响第一个,没有任何反应。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>test</title>
<style type="text/css">
    #firstElement:hover + #secondElement {
    color:red;
    }
    #secondElement:hover + #firstElement {
    color:blue;
    }
</style>
</head>
<body>
    <p id="firstElement">Hover</p>
    <p id="secondElement">Hello</p>
</body>
</html>

4 个答案:

答案 0 :(得分:2)

首先你需要将transition(如果你的意思是过渡而不是悬停)设置为这样的元素:

#firstElement:hover + #secondElement {
    color:red;
    transition:color 0.5s ease;  /* this is an example  */
}

#secondElement:hover + #firstElement {   /*  this is not right selector  */
    color:blue;
    transition:color 0.5s ease;  /* this is an example  */
}

第二,CSS中没有后退,你可以通过悬停第一个元素来改变第二个元素的颜色。

为此你可以使用jQuery。

使用此JQuery代码:

$("#secondElement").hover(function(){
    $("#firstElement").toggleClass("firstcolor");
});

并添加此CSS:

.firstcolor{
    color:blue;
}

here is DEMO

注意:这不仅仅是

的方式

答案 1 :(得分:2)

为什么这不起作用应该从其他答案中清楚。这是一个解决方案。

<div id="elements">
    <p id="firstElement">Hover</p>
    <p id="secondElement">Hello</p>
</div>

CSS

#elements:hover #secondElement:not(:hover) {
  color:red;
}
#elements:hover #firstElement:not(:hover) {
  color:blue;
}

DEMO

答案 2 :(得分:0)

psuedo悬停效果仅适用于父子关系。

所以,如果你有一个玩具是父母的菜单,芭比娃娃,汽车卡车和legos是3个子元素,你可以做psuedo课程。

例如,如果你做了

#toys:hover #barbiedolls { background: red; } 

这会奏效。但如果你尝试了

#barbiedolls:hover #toys { background: red; } 

这不起作用。

也不会
#barbiedolls:hover #cartrucks { background: red; }

答案 3 :(得分:0)

来自Adjacent sibling selectors

  

相邻的兄弟选择器具有以下语法:E1 + E2,其中E2是选择器的主题。如果E1和E2在文档树中共享相同的父级,并且 E1紧接在E2 之前,则选择器匹配,忽略非元素节点(例如文本节点和注释)。

这意味着#firstElement位于#secondElement之前,因此可行。

#secondElement不在#firstElement之前,因此不起作用。