简体   繁体   中英

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 position 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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM