2
  <div id="parent">
    <div id="children">
    </div>
  </div>

そして、親と子の両方を次のような同じイベントにバインドするとします。

     $("#parent").live({ mouseenter : Infocus , mouseleave : Outfocus });
     $("#children").live({ mouseenter : Infocus , mouseleave : Outfocus });

今、私の問題は、マウスを子供たちに向けると、親も強調表示されることです。誰かがここで何が起こっているのか教えてもらえますか?

4

2 に答える 2

2

stopPropagation()イベントフォローを防ぐために使用する必要があります。

function Infocus(e) {
  e.stopPropagation();
  // your code
}

function Outfocus(e) {
  e.stopPropagation();
  // your code
}

.stopPropagation()について読む

あなたはこのようなことをすることができます:(満足できないかもしれません)

$("#parent").live({
    mouseenter: Infocus,
    mouseleave: Outfocus
});
$("#children").live({
    mouseenter: Infocus,
    mouseleave: Outfocus
});

function Infocus(e) {
    if(this.id == 'parent') {
        $(this).css('background', 'yellow');
    } else if(this.id == 'children') {
        $(this).css('background', 'green');
        $(this).parent().trigger('mouseleave')
    }
}

function Outfocus(e) {
    if(this.id == 'parent') {
        $(this).css('background', 'transparent');
    } else if(this.id == 'children') {
        $(this).css('background', 'transparent');
        $(this).parent().trigger('mouseenter')
    }
}

デモ

于 2012-06-10T11:07:30.800 に答える
2

他の答えがある意味で正確であっても。あなたの問題は別の問題だと思います。あなたがしていると思うのはmouseenter、強調表示と強調表示の削除mouseleaveですが、実際に起こっていることは異なります。

#parent引っ越すときは絶対に離れません#children。画像でマウスを左(1)から右に動かした場合(5)にトリガーされるイベントは次のとおりです。

                +-----------------------------------+
                |#parent                            |
                |                                   |
                |                                   |
                |          +-------------+          |
                |          |#children    |          |
                |          |             |          |
          (1)   |    (2)   |     (3)     |   (4)    |   (5)
                |          |             |          |
                |          |             |          |
                |          +-------------+          |
                |                                   |
                |                                   |
                |                                   |
                +-----------------------------------+
  1. なし。
  2. #parent.mouseenter
  3. #children.mouseenter
  4. #children.mouseleave
  5. #parent.mouseleave

この場合は、ハイライト ロジックを変更する必要があります。

于 2012-06-10T11:24:20.440 に答える