我已经生成了一些简单的javascript,它们在每次页面刷新时随机分散div。
我注意到,有时div之一将放置在窗口边界之外。
我只是想找到一种始终将随机放置的图像包含在窗口内的方法。
感谢您的任何帮助或建议!
目前,我只是使用此javascript:
$(".pstn").each(function(i,el){
var tLeft = Math.floor(Math.random()*1000),
tTop = Math.floor(Math.random()*1000);
$(el).css({position:'absolute', left: tLeft, top: tTop});
});
最佳答案
要获得最大的left
var maxLeft = $(window).innerWidth() - $(el).innerWidth();
和最大top
var maxTop = $(window).innerHeight() - $(el).innerHeight();
然后您将其随机:
var tLeft = Math.floor(Math.random() * maxLeft),
tTop = Math.floor(Math.random() * maxTop);