2012-12-11 94 views
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(); 
    }); 
})(); 

但我想股利變黑上懸停,一個接一個。

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

但它不工作...

這裏是一個http://jsfiddle.net/q6L7C/2/

回答

4

Demo

它,因爲你的div的是動態生成的,請嘗試:

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

如果你使用的是舊版本的jquery,(> 1.7),則使用:

$(".destruct").live("mouseover", function(){ 
    $(this).css({background: '#000'}); 
}); 
+0

是的,謝謝你的工作! – Cat

+0

你想在mouseout上恢復到真實的顏色嗎? –

+0

不需要,但它可能對其他人有用。 :) – Cat

1

有幾種方法可以做到這一點。其一是事件代表團:

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

這將更改綁定:

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

...但我會嘗試比document用更具體的選擇。

另一種解決方案是綁定hover(或者在這種情況下爲mouseover,因爲它應該足夠)在每個div創建時分別回調每個div,但這會導致潛在的很多單獨的事件綁定。

+0

只是我的2ct:使用「懸停」不贊成jQuery 1.8支持「mouseenter mouseleave」 – devnull69

+0

@ devnull69使用'.hover',使用名爲'hover'的事件或兩者? –

+0

僅作爲「mouseenter mouseleave」的簡寫形式的「懸停」,因爲只能使用此方法將一個處理程序綁定到兩個處理程序。 '.hover()'還沒有被棄用(還) – devnull69

1

當您創建div時,您可以綁定.mouseenter(),或者您可以將.mouseenter()與其他答案指出的文檔(事件委託)綁定。我會用第一種方法去。 Updated demo

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