【问题标题】:Chrome and Firefox ignore Javascript style top and leftChrome 和 Firefox 忽略顶部和左侧的 Javascript 样式
【发布时间】:2015-07-14 23:01:37
【问题描述】:

我正在尝试使用 Javascript 中的样式,并尝试在我想要的位置放置一些 div。此代码在 Safari 中完美运行(每个 div 都放置在 left 和 top 表示的位置),但它不适用于 Chrome 和 Firefox。那不是

    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;

Chrome 和 Firefox 的问题是当我签入开发人员工具 style.top 和 style.left 时未定义,因此所有元素都显示在左上角。从开发者工具 -> 元素我得到了这个

<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>

与顶部和左侧无关...在 Safari 中它可以完美运行,并且元素被放置在它们应该在的位置。这是我从 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>

我用 Math.round() 试过了,但还是不行。

【问题讨论】:

  • 如果在该代码中设置断点,那么 div.x 和 div.y 的值是多少? chrome 和 firefox 都有开发者模式,所以你可以很容易地在代码中设置断点
  • this 指的是什么?你能给我们看一下完整的相关代码吗?
  • 好的!断点帮助我找到了错误...我不认为这可能是计算 div.x 和 div.x 的错误所以我从未检查过它们的值...问题来自 this.centerX 和 this.centerY是使用 document.width 和 document.height 计算的,这些在 safari 中有效,但在 firefox 或 chrome 中无效,所以在这两个返回的 NaN 中...我将它们更改为 window.innerWidth 和 window.innerHeight 并且在任何地方都可以完美工作.. . 谢谢!
  • 所以回答你自己的问题...
  • 是的,你可以回答你自己的问题:stackoverflow.com/help/self-answer

标签: javascript html css google-chrome safari


【解决方案1】:

解决了!

问题来自使用 document.width 和 document.height 计算的 this.centerX 和 this.centerY,这些在 safari 中有效,但在 firefox 或 chrome 中无效,因此在这两个中它们返回 NaN ...我更改了它们对于 window.innerWidth 和 window.innerHeight 并且在任何地方都能完美工作......谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    • 2012-08-14
    相关资源
    最近更新 更多