调整随机图像放置代码以实现灵活的布局



我正在寻找与此非常相似的效果:

http://jsfiddle.net/G5Xrz/

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 约束的图像,而是响应浏览器的尺寸。

以下代码段似乎有更合适的方法来生成随机位置:

http://jsfiddle.net/Xw29r/15/

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和浏览器高度和宽度(减去 50)作为适当的参数w

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"部分),你会得到这个:

js小提琴演示

<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);

这将在首次加载页面时更新容器的高度,并在放置随机图像时再次更新。更可靠的代码将具有单独的高度调整事件处理程序,该处理程序会在页面大小更改时更新高度。

最新更新