我有一个无序列表,希望添加以下效果:将某些内容附加到列表上后,它每次都会出现在屏幕上的随机位置。但是,由于它是列表中的文本,所以不能使每个随机位置重叠。附加的文本的淡出计时器为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的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基于窗口的高度和宽度以及列表项的声明的高度宽度。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句