0

私はJSとJQueryを初めて使用し、アニメーション化する要素を選択できません。これが私のHTMLです。

    <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')
});

しかし、何も起こらないので、助けが必要です。

ありがとう!

4

6 に答える 6

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')
});
于 2012-08-03T04:51:35.037 に答える
2

.prev()目的h2の は の前の兄弟であるため、選択したアイテムの祖先を検索して一致するものを検索しfigureます。.closest()

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

フィドル

于 2012-08-03T04:52:10.303 に答える
1

closest()親ノード間で、DOM ツリーの要素を返します。hovered の前に要素を取得する必要があるsiblings("h2")か、単に取得する必要があります。prev()<figure>

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

selector から始めて、or$('.box-product')を使用できますが、ドキュメント全体でそれらすべてを選択します。ボックスがユニークな場合は、次のようなものも使用できます。find("h2")children("h2")$("#box-product h2")

于 2012-08-03T04:53:04.663 に答える
1

h2の兄弟ですfigure

$('.box-product figure').hover(function() {
    $(this).siblings('h2').animate({color: '#f00'}, 'slow')
}, function() {
    $(this).siblings('h2').animate({color: 'inherit'}, 'slow')
});
于 2012-08-03T04:53:16.753 に答える
0

これを試してください...最も近い最初の要素...

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

フィドル

于 2012-08-03T04:53:36.753 に答える
0

closest()メソッドは、子要素や兄弟からではなく、親階層から最も近い一致を見つけます。

あなたの場合、親から子要素を見つけるだけです。このような:

 $('.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')
 });
于 2012-08-03T04:57:16.843 に答える