http://jsfiddle.net/4a7Tj/2/
为了让列表项显示在随机位置,应该为此创建 CSS,position:absolute
然后根据生成的随机值设置左侧和顶部
CSS
li{
height: 20px;
background: orange;
width:200px;
margin:2px;
padding:5px;
position: absolute;
}
ul{
list-style:none;
}
JavaScript
$(document).ready(function(){
$('#typetextbox').keypress(function (e){
if(e.keyCode == 13 ) $('#submit').click();
});
$('#submit').click(function(){
var message = $('#typetextbox').val();
if (message.replace(/ /g, '')){
var positions = makeNewPosition();
var el = $('<li>'+message+'</li>');
el.attr('gridpos', positions[0].toString()+"x"+positions[1].toString())
el.css('left', positions[1] * window.li_width);
el.css('top', positions[0] * window.li_height);
$('#messagebox').append(el);
setTimeout(function() {
el.fadeOut();
var gridpos = el.attr('gridpos');
delete window.grid[gridpos];
}, 5000 );
}
$("#typetextbox").val("");
});
});
window.grid = {};
window.li_height = 20;
window.li_width = 200;
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = Math.floor($(window).height()/window.li_height);
var w = Math.floor($(window).width()/window.li_width);
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
var gridpos = nh.toString() + "x" + nw.toString();
if(typeof window.grid[gridpos] == 'undefined'){
return [nh,nw];
}else{
//this could eventually run out of room, so make sure to clear the grid with delete window.grid[gridpos]; when it disappears from the screen.
return makeNewPosition();
}
}
gridpos 基于窗口的高度和宽度以及列表项的声明高度宽度。