我发现这段代码可以随机创建一些 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 在悬停时变成黑色,一个接一个。
$(document).ready(function() {
$('.destruct').hover( function(){
$('.destruct', this).css({background: '#000'});
});
});
但它不起作用......
最佳答案
因为你的div是动态生成的,试试:
$(document).ready(function() {
$(document).on('mouseover', '.destruct', function(){
$(this).css({background: '#000'});
});
});
如果您使用的是旧版本的 jquery,(>1.7),请使用:
$(".destruct").live("mouseover", function(){
$(this).css({background: '#000'});
});
关于javascript - div 的随机位置和悬停功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13817763/