【问题标题】:Is there a bug in Safari with getComputedStyle?Safari 中是否存在带有 getComputedStyle 的错误?
【发布时间】:2014-07-19 04:09:04
【问题描述】:

据我所知,safari 和 chrome 都是基于 webkit 的浏览器,但是当我使用 getComputedStyle 时,它​​看起来不同。 Chrome、IE、FF 都回显“50px”,但 Safari 回显“10%”。 这对工作来说真的很不方便。 这是一个 safari 错误还是我只是弄错了?

Safari中win V5.1.7和IOS6/7的demo测试 这是一个演示:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0; padding:0;}
body{
    position: relative;
    height: 500px;
}
#test{
    position: absolute;
    top: 10%;
    left: 10%;
    width: 100px;
    height: 100px;
    background-color: #000;
}
</style>
<script>
window.onload = function () {
    var oTest = document.getElementById('test');
    var iLeft = window.getComputedStyle(oTest, null)['top'];
    console.log(iLeft);
    alert(iLeft);
}
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>

【问题讨论】:

    标签: javascript html safari webkit


    【解决方案1】:

    bug 仍然存在于 Safari 7.1 中。 Blink 引擎为 Chrome 应用了patch 以匹配 IE9 和 Firefox 行为。但遗憾的是,该更改尚未移植到 Webkit。

    CSSOM spec 并没有真正定义 getComputedStyle 最初应该返回的内容,其中一些是 still not fully 直到今天,由于浏览器的差异。这有点互操作的混乱。

    我想说要么避免百分比,或者以您的示例为例,您必须通过在 body 上执行 getComputedStyle 除以 10 来实现跨浏览器兼容性 fallback method

    【讨论】:

      【解决方案2】:

      你可以使用:

      var font = "10%"; // suppose got 10%
      if (font.indexOf("%") > -1) {
          font = font.substr(0, font.length - 1);   // get the `10`
          font = parseInt(font, 10);  // convert to number
          var w = window,
              d = document,
              e = d.documentElement,
              g = d.getElementsByTagName('body')[0],
              width = w.innerWidth || e.clientWidth || g.clientWidth;  // the width
      
          alert((font * width) / 100);  // alert (percent * width / 100)
      } else {
          alert(font); // font is normal (in px,etc.)
      }
      

      Live Demo

      编辑 1:

      试试这个:

      var oTest = document.getElementById('test');
      var iLeft = window.getComputedStyle(oTest).getPropertyValue("top");
      alert(iLeft);
      

      This again works for me。我还在Mobile Safari simulator 上进行了尝试,得到了正确的结果。但可能是模拟器的移动设备,而您使用的是桌面设备。顺便说一句,您使用的是最新的 Safari 版本吗?

      【讨论】:

      • 嗯,可以,但 safari 应该为我做到这一点,对吧?
      • @user2926630 是的,但我只是为这个问题提供了一个解决方法。
      • 感谢您的编辑,但它仍然在 Safari 中提醒 '10%' for win v5.1.7 和 ios6/7
      • @user2926630 那我真的很抱歉我不知道。
      • @HighBoots 如果您设置了px 值但不适用于%,它会起作用。原因见我的answer
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      相关资源
      最近更新 更多