3

私はこのコードがランダムにいくつかのdivを作成することを発見しました:

(function makeDiv(){
   var divsize = ((Math.random()*100) + 50).toFixed();
   var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
   $newdiv = $('<div/>').addClass("destruct").css({
       'width':divsize+'px',
       'height':divsize+'px',
       'background-color': color
   });

   var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
   var posy = (Math.random() * ($(document).height() - divsize)).toFixed();

   $newdiv.css({
       'position':'absolute',
       'left':posx+'px',
       'top':posy+'px',
       'display':'none'
   }).appendTo( 'body' ).fadeIn(500, function(){
      makeDiv(); 
   }); 
})();

しかし、ホバー時にdivを1つずつ黒に変えてほしい。

$(document).ready(function() {
  $('.destruct').hover( function(){
    $('.destruct', this).css({background: '#000'});
   });
});

しかし、それは機能しません...

これがhttp://jsfiddle.net/q6L7C/2/です

4

3 に答える 3

4

デモ

divが動的に生成されるため、試してください:

$(document).ready(function() {
   $(document).on('mouseover', '.destruct', function(){
      $(this).css({background: '#000'});
   });
});

古いバージョンの jquery (>1.7) を使用している場合は、次を使用します。

$(".destruct").live("mouseover", function(){
    $(this).css({background: '#000'});
}); 
于 2012-12-11T10:03:50.370 に答える
1

これを行うにはいくつかの方法があります。1 つはイベント委任です。

http://jsfiddle.net/q6L7C/3/

これにより、バインディングが次のように変更されます。

$(document).on('hover', '.destruct', function(){
   $(this).css({background: '#000'});
});

...しかし、より具体的なセレクターを使用しようとしますdocument

別の解決策は、div が作成されるたびにコールバックを各 div に個別にバインドすることですhover(または、この場合はそれで十分なはずです)。mouseover

于 2012-12-11T10:03:52.303 に答える
1

他の回答が指摘したように、div を作成する.mouseenter()ときにバインドするか、ドキュメント (イベント委任) にバインドできます。.mouseenter()最初の方法で行きます。更新されたデモ

(function makeDiv(){
    var divsize = ((Math.random()*100) + 50).toFixed();
    var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
    $newdiv = $('<div/>').addClass("destruct").css({
        'width':divsize+'px',
        'height':divsize+'px',
        'background-color': color
    })
    // Magic happens here!
    .mouseenter(function(){
      $(this).css({background: '#000'});
    });

    var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
    var posy = (Math.random() * ($(document).height() - divsize)).toFixed();

    $newdiv.css({
        'position':'absolute',
        'left':posx+'px',
        'top':posy+'px',
        'display':'none'
    }).appendTo( 'body' ).fadeIn(500, function(){
       makeDiv();
    });
})();
于 2012-12-11T10:07:13.100 に答える