绝对位置元素,因此它们表现得像浮动一样

时间:2013-04-23 13:27:38

标签: javascript css

我想让所有这些盒子表现得像浮动一样。然而,他们不可能,他们需要绝对定位,以便我与这个定位的数字进行交互。

这是我的尝试:

var $item = $('#wrapper div'),
    len = $item.length,
    itemWidth = $item.innerWidth(),
    winWidth = $('#wrapper').innerWidth(),
    cols = Math.floor(winWidth / itemWidth),
    moveX = itemWidth + 10;

function absPos() {
    for (var i = 0; i < len; i += 1) {
        $('.item-' + i).css({
            'position' : 'absolute',
            'left' : moveX * i
        });
    }
}

我无法弄清楚如何将它们包裹起来以适应,并在调整窗口大小时重新定位。

这是一个演示。 http://jsfiddle.net/Fgcqs/3/。如果取消对absPos()函数的修改,你会看到我的开始。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

您必须跟踪column indexrow indexcolumn index * item width超过window width后,重置column index并增加row index以模拟下一行。以下是此方法的简单示例:

function absPos() {
    var colIndex = 0;
    var rowIndex = 0;
    for (var i = 0; i < len; i += 1) {
        if (moveX * colIndex + itemWidth > winWidth) {
            colIndex = 0;
            rowIndex++;
            top += itemHeight + 10;
        }
        var left = moveX * colIndex; 
        var top = moveY * rowIndex;
        $('.item-' + i).css({
            'position' : 'absolute',
            'left' : left,
            'top' : top
        });
        colIndex++;
    }
}

http://jsfiddle.net/N4S4L/1/

答案 1 :(得分:1)

我已经编辑了你的jsfiddle来移动它们浮动的项目。假设包装器中每个div的边距和宽度相同,并且如果css发生变化,它将自动计算出间距的宽度和高度

var wrapper =  $('#wrapper'),
    items = wrapper.children('div'),
    len = items.length,
    itemWidth = items.innerWidth() + parseInt(items.css('margin-left')) + parseInt(items.css('margin-right')),
    itemHeight = items.innerHeight() + parseInt(items.css('margin-top')) + parseInt(items.css('margin-bottom'));

items.css('float', 'none');


function absPos() {
    var cols = Math.floor(wrapper.width() / itemWidth);
    items.each(function() {

        var left = ($(this).index() % cols) * itemWidth; //the bit in brackets calculates which column the div should be in (the remainder of the current index of your item divided by the number of columns per row), then you times that by item width as worked out above, you use the index as this will allow you to start at left:0

        var height = Math.floor($(this).index() / cols) * itemHeight //the bit in brackets calculates which row the div should be in, then you times that by item height as worked out above, you use the Math.floor as this will allow you to start at top:0.  Should have really called this top!

        $(this).css({
            'position' : 'absolute', 
            'top': height,
            'left': left
        });
    });

    wrapper.height((Math.ceil(len / cols)) * itemHeight);
}

$(window).resize(function() {
    absPos();
});
absPos();

http://jsfiddle.net/Fgcqs/12/

答案 2 :(得分:0)

您应该检查值加上项目的宽度是否超​​过容器的宽度,在这种情况下引入 top 值并重置 left 为0以开始构建新行。