2011-12-23 189 views
22

我看了幾個其他問題,但我似乎無法找出他們中的任何一個,所以這裏是我的問題,我想有一個div或跨度,當你懸停在它上面會出現一個區域,並且會像下降一樣。如何更改一個元素,而另一個徘徊

比如我有一個DIV,我想在它懸停,並將它顯示有關我徘徊了項目的一些信息在

<html> 
<head> 
<title>Question1</title> 

<styles type="css/text"> 

#cheetah { 
    background-color: red; 
    color: yellow; 
    text-align: center; 
} 

a { 
    color: blue; 
} 

#hidden { 
    background-color: black; 
} 

a:hover > #hidden { 
    background-color: orange; 
    color: orange; 
} 
</styles> 

</head> 
<body> 
<div id="cheetah"> 
    <p><a href="#">Cheetah</a></p> 
</div> 
<div id="hidden"> 
    <p>A cheetah is a land mammal that can run up 2 60mph!!!</p> 
</div> 
</body> 
</html> 

但這^似乎沒有工作,我不知道爲什麼。 ..如果有辦法做到這一點在CSS中,我想知道,但我想任何和所有的建議。

+0

在問題的底部查看我的意見。那裏還有一個小提琴。如果選擇chnaging你的html結構是一個選項 - http://stackoverflow.com/questions/6669147/css-change-two-links-when-hovering-over-either-one-of-them – Jawad 2011-12-23 10:00:26

+0

in jquery http: //jsfiddle.net/amkrtchyan/e8wJb/ – 2011-12-23 10:15:38

回答

17

您可以在不影響使用:hover從CSS2中非子元素,受所有常見瀏覽器支持。

可以使用CSS2.1選擇影響一個兄弟元素,像這樣:

a:hover + .sibling { ... } 

然而,這僅適用於直接兄弟姐妹。這意味着你可以有HTML這樣的:

<p><a href="#">Cheetah</a> <span class="sibling">Blah Blah Blah</span></p> 

注意,aspan是直接的兄弟姐妹。

這裏的示出對兄弟姐妹小提琴:http://jsfiddle.net/vUUxp/

但是,not all browsers support the CSS2.1 sibling selectors,所以你需要決定根據你的目標受衆,如果你可以使用這個與否。

編輯:糾正對CSS版本爲+選擇我的錯誤:它是2.1,定義它,而不是CSS3。我還添加了一個顯示瀏覽器支持的鏈接。否則,答案是一樣的。

+1

也有[通用兄弟選擇器](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors),但它們也僅適用於後續分子 – spelufo 2015-03-01 15:44:19

10

或者,如果您打開它,請使用jQuery

像這樣的工作:

$("#element") // select your element (supports CSS selectors) 
    .hover(function(){ // trigger the mouseover event 
     $("#otherElement") // select the element to show (can be anywhere) 
      .show(); // show the element 
    }, function(){ // trigger the mouseout event 
     $("#otherElement") // select the same element 
      .hide(); // hide it 
    }); 

記住在DOM就緒功能($(function(){...});$(document).ready(function(){...});)來包裝這一點。