简体   繁体   中英

changing the position of absolute divs inside a relative div only works with the number 0

I have a main relative DIV. Inside that div i have a few absolute div's with images. Example of a part of the code below:

   <div  id="loopdiv" style="position:absolute; left:0px; top:0px; width:2000px; height:1333px;">
        <div style="position:absolute; left:0px; top:0px; width:2000px; height:25px;">
            <img id="index_01" src="image3/index_01.jpg" width="2000" height="25" alt="" />
        </div>
        <div style="position:absolute; left:0px; top:25px; width:102px; height:1308px;">
            <img id="index_02" src="image3/index_02.jpg" width="102" height="1308" alt="" />
        </div>
....
...

I want to change the position of those relative divs with javascript. This is my javascipt code:

var divs = new Array();
var loopdiv = document.getElementById('loopdiv');
divs =loopdiv.getElementsByTagName('div'); 

for (var i=0;i<divs.length;i++){ 
divs[i].style.position ="absolute";
divs[i].style.left=0;
divs[i].style.top=0;
alert(divs[i].style.left+"||"+i);
alert(divs[i].style.right+"||"+i);

The strange thing is that the value 0 in the javascript works. All the divs go to 0,0 position. But if i try to set the value to another number. For example:

divs[i].style.left=300;
    divs[i].style.top=300;

Now the divs stay at their position from the HTML. They don't go to 300 or any other number i put in. Only 0.

Does anyone know why?

you're not defining a unit identifier.

in your original case, where you're zeroing the position, you're effectively doing:

divs[i].style.left=0 === divs[i].style.left='0px';

...so to get your example to work with pixels , use px :

divs[i].style.left = 300; --> divs[i].style.left = '300px' ;


UPDATE

To qualify my answer, check out the CSS values and units spec: http://www.w3.org/TR/REC-CSS1/ . Notice how it says that the unit identifier is only optional if the value is 0.

The format of a length value is an optional sign character ('+' or '-', with '+' being the default) immediately followed by a number (with or without a decimal point) immediately followed by a unit identifier (a two-letter abbreviation). After a '0' number, the unit identifier is optional.

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