6

クエリの hover メソッドを使用すると、ユーザーがホバーしたときに何が起こるか、ユーザーがホバーを外したときに何が起こるかを指定できることを知っています。ただし、コンテンツが動的に作成されるため、ホバー イベントを処理するために .on() を使用しています。ユーザーがホバーを外したときに元の状態に戻すにはどうすればよいですか。これが私のコードです。私は .off() を試しましたが、探している結果が得られませんでした:

$('tr').on('hover', 'td', function(){
    $(this).fadeTo(500, 1 )    
})

これが私が試したことです:

$('tr').off('hover', 'td', function(){
    $(this).fadeTo(500, .85 )         
})

ありがとう。

4

5 に答える 5

12

を使用する場合.on()、ハンドラへのイベントは「mouseenter」と「mouseleave」です。1回の呼び出しでそれを行うことができます:

$('tr').on({
  mouseenter: function() {
    $(this).fadeTo(500, 1); // or whatever
  },
  mouseleave: function() {
    $(this).fadeTo(500, 0.85); // or whatever
  }
}, 'td');

「:hover」疑似クラスを使用して、CSS でこれを行うこともできます。これは、古いバージョンの IE でもある程度は機能します。変更をアニメーション化することもできます。

于 2013-08-12T14:25:30.033 に答える
11

これはあなたが必要とするものです

$('tr').on('mouseenter', 'td', function(){

    $(this).fadeTo(500, 1 )

}).on('mouseleave', 'td', function(){

    $(this).fadeTo(500, .85 )


})
于 2013-08-12T14:26:54.410 に答える
6

純粋なCSSでそれを行うことができますが、ここに行きます:

$('tr').on('mouseenter mouseleave', 'td', function( e ){       
    $(this).fadeTo(500, e.type=="mouseenter" ? 1 : 0.85 );    
});

ホバーの使用:

$('tr td').hover(function( e ){       
    $(this).fadeTo(500, e.type=="mouseenter" ? 1 : 0.85 );    
});

ヒント:メソッド参照を使用する場合のよう
.on('hover'に、イベントへの直接参照を個別にバインドするのではなく、イベントのみをバインドします。mouseenter mouseleave$(selector).hover(handlerIn, handlerOut)hover

再開します:

$('tr').on('hover', 'td', function( e ){       
   // no separated "mouseenter" and no "mouseleave" e.type reference here :(
   // just "hover" event
});

$('tr').on('mouseenter mouseleave', 'td', function( e ){       
   // e.type are defined :)
});

$('tr').on('mouseenter', 'td', function( e ){       
   // function only for 'mouseenter' event
}).on('mouseleave', 'td', function(){
   // function only for 'mouseleave' event
});

$('tr td').hover(function( e ){       
   // e.type "mouseenter" and "mouseleave" are in event reference :)
});

// $("tr td").hover(handlerIn, handlerOut)

$('tr td').hover(function(){       
   // Method default // e.type reference == "mouseenter" 
}, function(){
   // Method default // e.type reference == "mouseleave" 
});

.on()(動的に作成された要素)を使用してイベントを要素に委任する必要があるか、それとも.hover()ニーズに適しているかによって異なります。

メソッドに関しては、.off()それが何をするかを詳しく見ることができます: here
基本的に、ある時点で、.off() を使用するよりも要素へのイベント委譲をさらに削除したい場合:

$('#selector').on('click', 'button', function(){

  // Function callback:
  alert('I will alert only once cause of off()');
  $('#selector').off('click', 'button');

});
于 2013-08-12T14:25:45.813 に答える
3

ホバーはイベントではなく、イベントハンドラーのmouseenterショートカットmouseleaveです

$('tr').on('mouseenter', 'td', function(){
    $(this).fadeTo(500, 1 )
}).on('mouseleave', 'td', function(){
    $(this).fadeTo(500, .85 )
})
于 2013-08-12T14:25:53.357 に答える
0
$('.element').hover(
    function () {
        $(this).fadeTo(500, 1);
    }, 
    function () {
        $(this).fadeTo(500, .85);
    }
);
于 2013-08-12T14:40:34.530 に答える