开发者

Pin all elements to top of div using JS, but keep horizontal position

开发者 https://www.devze.com 2023-03-05 04:24 出处:网络
I have a series of square <li> elements inside a fixed width ul.As they reach the edge of the <ul>, they drop onto a new row, so there are 3 rows of <li>s (imagine a brick wall made

I have a series of square <li> elements inside a fixed width ul. As they reach the edge of the <ul>, they drop onto a new row, so there are 3 rows of <li>s (imagine a brick wall made up of <li> elements).

I need to pin all of these to the top 开发者_如何学编程edge of the <ul>, so there's only one row, with all of them layered on top. The problem is that if I use position: absolute; top:0;, the horizontal position is lost.

Is there any way of doing this with javascript so that the horizontal position is retained, but they are pinned to the top of the <ul>? It doesn't matter that they'll all overlap and stack on top of each other


You have to let them layout naturally and then change their style to position:absolute, top:0 and left:(insert the value of each element's offsetLeft).

edit: example

var container = document.getElementById('hover-days');
var elements = container.getElementsByTagName('li');
var lefts = [];

// first read the values
for(var i = 0; i < elements.length; ++i) {
    lefts[i] = elements[i].offsetLeft;
}

// then set them
for(var i = 0; i < elements.length; ++i) {
    var el = elements[i];
    el.style.left = lefts[i] + 'px';
    el.style.top = '0px';
    el.style.position = 'absolute';
}


If you can use CSS3 selectors, :nth-child() pseudo selector can help you (you have a fixed width list, so I assumed you will always have the same number of lis in a row).

ul { width: 150px; height: 150px; position: relative; }

li { width: 50px; height: 50px; position: absolute; top: 0; left: 0; }

li:nth-child(3n-1) { left: 50px; }

li:nth-child(3n) { left: 100px; }

jsFiddle Demo

In case you need a jQuery solution, I wrote this little neat function:

$('li').css('left', function (index) {
    var $me=$(this),
        myWidth=$me.width(),
        myLeft=(index % 3)*myWidth;
    return myLeft;
});

This code assumes that li are already set to position: absolute; top: 0; and the ul to position: relative and all widths and heights are set using CSS.

2nd jsFiddle Demo

Reading your comments, just use #hover-days ul li instead of li as the jQuery selector.

0

精彩评论

暂无评论...
验证码 换一张
取 消