Change various elements style.left and top with script?
I have this loop that produces many elements with different positions:
if ( $row['Type'] == "house") { ?>
<div class="itemW" style="margin-left: <?=$row['X']?>px; margin-top: <?=$row['Y']?>px;">
Item
</div> <?
}
I need to change all the divs left position, I'm trying this:
var items = document.getElementsByClassName("itemW");
items[0].style.left = land.width() / items[0].style.left * 100;
The problem is that items[0].style.left
doesn't get the po开发者_JAVA百科sition of the first div. Also I don't know how to do it with all the divs.
You can get all elements with a particular class name with
document.getElementsByClassName("classname");
for anything but IE < 9 at least :P
Then it's just a matter of looping through them like so
var meh = document.getElementsByClassName("classname");
for (var i = 0; i < meh.length; i++)
meh[i].style.left = land.width() / items[0].style.left * 100 + "px"; // "px" is very important.
// also this will only work
// if you have first set the
// element's style attribute.
Try this with jQuery:
$('.itemW').each(function () {
var item = $(this);
var pos = item.position();
item.css('left', (item.width() / pos.left * 100) + 'px');
item.css('top', (item.height() / pos.top * 100) + 'px');
});
精彩评论