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

时间:2013-09-06 15:20:54

标签: javascript jquery

我正在寻找与此类似的效果:

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,我不知道如何将两者结合起来。

有人可以帮忙吗?

由于

1 个答案:

答案 0 :(得分:0)

从第二段代码中取出这部分:

// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;

并将这些变量hw与浏览器的高度和宽度(减去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);

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