我正在寻找与此非常相似的效果:
function rnd(max) { return Math.floor(Math.random()*(max+1)) }
function showImage(container, maxwidth, maxheight, imgsrc, imgwidth, imgheight) {
var id = "newimage" + rnd(1000000);
$(container).append(
"<img id='" + id + "' src='" + imgsrc +
"' style='display:block; float:left; position:absolute;" +
"left:" + rnd(maxwidth - imgwidth) + "px;" +
"top:" + rnd(maxheight - imgheight) + "px'>");
$('#' + id).fadeIn();
return id;
}
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
但我更喜欢灵活的布局,即图像不受具有预定义高度和宽度的 div 的约束,而是响应浏览器的尺寸。
下面的代码似乎有更合适的方式来生成随机位置:
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
但是我是 javascript 的初学者,我不知道如何将两者结合起来。
有人可以帮忙吗?
谢谢
最佳答案
从第二个代码中获取这部分:
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
并使用这些变量 h
和 w
以及浏览器高度和宽度(负 50)作为第一个代码的这部分中的适当参数:
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
此外,第一个代码具有以下 HTML:
<div id="container" style="width:400px; height:600px; background: green; position:relative"></div>
以像素值对高度和宽度进行硬编码。您可以使用 CSS 百分比值来使宽度响应父容器的大小。然而,你需要 JS 来正确设置高度;高度的百分比没有任何作用
将所有内容放在一起(并删除“负 50”部分),您将得到:
<强> jsFiddle demo
<div id="container" style="width:100%; height:100px; background: green; position:relative"></div>
function adjustContainerHeight(height) {
$('#container').height(height);
}
adjustContainerHeight($(window).height());
setInterval(
function() {
var h = $(window).height();
var w = $(window).width();
adjustContainerHeight(h);
showImage("#container", w, h,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
这会在页面首次加载时更新容器的高度,并在放置随机图像时再次更新。更健壮的代码将有一个单独的高度调整事件处理程序,每当页面大小发生变化时,它就会更新高度。
关于javascript - 采用随机图像放置代码以实现灵活的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18661176/