我有一个无序列表,我希望添加这样的效果:当向其中添加某些内容时,它每次都会出现在屏幕上的随机位置。但是,由于它是列表中的文本,因此我不能让每个随机位置重叠。附加的文本将有一个 5 秒的淡出计时器,因此一旦消息淡出,该空间将变得可用。
这可能吗?如果是的话,这里是我正在使用的 HTML:
<ul id="messagebox" >
</ul>
<div>
<input type="text" id="typetextbox" maxlength="120" autocomplete="off" />
<button type="submit" id="submit" onblur="submit"> </button>
</div>
这是 Javascript/jquery:
$(document).ready(function(){
$('#typetextbox').keypress(function (e){
if(e.keyCode == 13 ) $('#submit').click();
});
$('#submit').click(function(){
var message = $('#typetextbox').val();
if (message.replace(/ /g, ''))
$('#messagebox').append(message + "<br/>");
$("#typetextbox").val("");
});
});
如果没有,我该怎么做才能达到这种效果?
谢谢大家!
最佳答案
为了让列表项显示在随机位置,CSS 应该设置为 position:absolute
然后根据生成的随机值设置 left 和 top
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();
}
}
网格位置基于窗口的高度和宽度以及列表项声明的高度宽度。
关于javascript - 分散的无序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25149767/