2012-08-03 78 views
0

我在JS和JQuery真正的新,我未能在選擇動畫一個元素選擇一個元件附近的第一H2,這是我的HTML與jQuery

<div class="box-product"> 
     <h2>Light</h2> 
     <figure> 
     <img src="img/boxes/light.jpg" alt="Pepper Box Light" title="Pepper Box Light" /> 
     <figcaption> 
      Versão light, porém igualmente apimentada da nossa PepperBox, para quem quer se divertir com seu amor</figcaption> 
     </figure>   
    </div><!-- box-product --> 

我試圖選擇該h2當用戶將鼠標懸停在figure,所以這是我最好的猜測:

$('.box-product figure').hover(function() { 
    $('.box-product').closest('h2').animate({color: 'f00'}, 'slow') 
}, function() { 
    $('.box-product').closest('h2').animate({color: 'inherit'}, 'slow') 
}); 

但沒有任何反應,所以,我需要一些幫助。

謝謝!

回答

2

closest():

獲取的選擇相匹配,開始在當前元素,並通過DOM樹前進了第一個元素。

您可以使用prev()方法:

$('.box-product figure').hover(function() { 
    $(this).prev().animate({color: '#f00'}, 'slow') 
}, function() { 
    $(this).prev().animate({color: 'inherit'}, 'slow') 
}); 

或:

$('.box-product figure').hover(function() { 
    $(this).siblings('h2').animate({color: '#f00'}, 'slow') 
}, function() { 
    $(this).siblings('h2').animate({color: 'inherit'}, 'slow') 
}); 
+0

感謝您的快速回答,這工作,但就像我說過那裏,顏色設置爲'F00',沒有正確它'#F00'什麼也沒有發生。 – 2012-08-03 05:18:25

+0

@EduardoRuiz不客氣,是的,這是一個錯字。 – undefined 2012-08-03 05:20:37

2

使用.prev(),因爲期望h2figure以前的兄弟,.closest()搜索所選項目的祖先一場比賽。

$('.box-product figure').hover(function() { 
    $h2 = $(this).prev('h2'); 
    $h2.animate({color: '#f00'}, 'slow') 
}, function() { 
    $h2.animate({color: '#000'}, 'slow') 
}); 

FIDDLE

1

closest()返回元件向上在DOM樹中,父節點之中。您需要siblings("h2")或只是prev()懸停<figure>之前得到的元素:

$('.box-product figure').hover(function() { 
    $(this).prev().animate({color: 'f00'}, 'slow') 
}, function() { 
    $(this).prev().animate({color: 'inherit'}, 'slow') 
}); 

與選擇$('.box-product')開始,你可以使用find("h2")children("h2"),但是這將在整個文檔中選擇所有。如果你的盒子是獨一無二的,你也可以使用類似$("#box-product h2")的東西。

+0

嘿,'prev()'也工作過了,正如我在那裏說的那樣,我輸入了錯誤的顏色,沒有改變它到'#f00'什麼都沒有發生,並且在Firefox JS檢查器上沒有顯示錯誤。 – 2012-08-03 05:14:50

1

h2figure的兄弟姐妹。

$('.box-product figure').hover(function() { 
    $(this).siblings('h2').animate({color: '#f00'}, 'slow') 
}, function() { 
    $(this).siblings('h2').animate({color: 'inherit'}, 'slow') 
}); 
+0

達姆,我嘗試了所有的答案,沒有任何改變,然後我看到'f00'的顏色,只是放了'#',這個工作正常,謝謝! – 2012-08-03 05:11:42

0

嘗試...... 最近的第一個元素...

​$('h2').siblings(':first')​;​ 

Fiddle

0

最接近()方法找到最接近從父母的層次結構,而不是從子元素,也不是兄弟姐妹的比賽。

在你的情況下,你需要從父母中找到子元素。像這樣:

$('.box-product figure').hover(function() { 
    $(this).closest('.box-product').find('h2').animate({color: 'f00'}, 'slow') 
}, function() { 
    $(this).closest('.box-product').find('h2').animate({color: 'inherit'}, 'slow') 
});