简体   繁体   中英

Chrome and Firefox ignore Javascript style top and left

I'm playing a little with styles from Javascript and I'm trying to place some div where I want. This code works perfectly in Safari (where every div is placed where left and top says) but it does not work on Chrome and Firefox. That are not the

    div = document.createElement('div');
    div.id = this.numberOfSystem + 'circle' + i;


    div.x = ((this.centerX) + ((this.lenghtMain/2 + this.lenghtSmall/2 + 50) * Math.sin( 2 * Math.PI / this.amount * i))) - (this.lenghtSmall / 2);  
    div.y = ((this.centerY) + ((this.lenghtMain/2 + this.lenghtSmall/2 + 50) * Math.cos( 2 * Math.PI / this.amount * i))) - (this.lenghtSmall / 2);

    div.style.position = "fixed";
    div.style.left = div.x + "px";
    div.style.top = div.y + "px";
    div.style.width = this.lenghtSmall;
    div.style.height = this.lenghtSmall;

The problem with Chrome and Firefox is when I check in developer tools style.top and style.left are not defined so all the elements appears positioned at the top left corner. From developer tools -> elements i get this

<div id="0circle1" style="position: fixed; width: 250px; height: 250px; text-align: center; background-image: url(file:///Users/Imanol/Documents/Webs/Portfolio2/circulo200.png); background-size: 100%;"><div style="margin: 20%;">Curriculum</div></div>

Nothing about top and left... In Safari it works perfectly and the elements are placed in the places they are meant to be. This is what a I get from Safari.

<div id="0circle0" style="position: fixed; left: 340.0003905596077px; top: 360.04122042944215px; width: 250px; height: 250px; background-image: url(file:///Users/Imanol/Documents/Webs/Portfolio2/circulo200.png); background-size: 100%; text-align: center;"><div style="margin: 20%;">Studies<br><br><img width="100" height="100" src="pastel.jpg"></div></div>

I tried with Math.round() but it still doesn't work.

Solved!

The problem came from this.centerX and this.centerY that were calculated using document.width and document.height and these worked in safari but not in firefox or chrome, so in these two they returned NaN... i changed them for window.innerWidth and window.innerHeight and work perfect everywhere... thank you!

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