Modernizr位置固定测试不完整

Modernizr position fixed test incomplete

本文关键字:测试 位置 Modernizr      更新时间:2023-09-26

Modernizr很棒,但position: fixed的示例测试非常不完整:

  • iOS 4及更低版本在不支持position: fixed的情况下返回true
  • Windows上的Opera返回false,但它确实支持position: fixed

我发现了另一个基于Modernizr测试的测试,但添加了iOS检测:https://gist.github.com/855078/109ded4b4dab65048a1e7b4f4bd94c93cebb26b8.由于即将推出的iOS5确实支持position: fixed,因此它并不能真正经得起未来的考验。

你们能帮我找到一种不用浏览器嗅探就能在iOS中测试固定位置的方法吗?

// Test for position:fixed support
Modernizr.addTest('positionfixed', function () {
    var test  = document.createElement('div'),
      control = test.cloneNode(false),
         fake = false,
         root = document.body || (function () {
            fake = true;
            return document.documentElement.appendChild(document.createElement('body'));
      }());
   var oldCssText = root.style.cssText;
   root.style.cssText = 'padding:0;margin:0';
   test.style.cssText = 'position:fixed;top:42px';
   root.appendChild(test);
   root.appendChild(control);
   var ret = test.offsetTop !== control.offsetTop;
   root.removeChild(test);
   root.removeChild(control);
   root.style.cssText = oldCssText;
   if (fake) {
      document.documentElement.removeChild(root);
   }
   return ret;
});

我为iOS编写了这个测试:http://mnobeta.no/2011/09/test-position-fixed-for-iphone/

它有点乱,但似乎能用。安卓仍然是一个问题,因为它的"假"position:fixed

我发现你需要插入一些技巧来获得功能定位固定测试。例如,我在测试中插入了一个破解,该破解对于运行v.5或更高版本的iOS设备返回true:

/*iPhone/iPad Hack*/
if(navigator.userAgent.match(/iPad|iPhone/i) !== null){
    /*Check if device runs iOS 5 or higher*/
    isSupported = navigator.userAgent.match(/[5-9]_[0-9]/) !== null;
}

我不确定这个代码有多"干净",但它对我来说很有用。