检测位置:用javascript修复

时间:2011-05-10 11:00:35

标签: javascript jquery mobile

我试图从这里使用Kangax的脚本:http://kangax.github.com/cft/来检测那些“正确”实现位置的浏览器:固定为桌面浏览器,与移动浏览器相比,所以我可以使用jQuery在移动浏览器上伪造它。

来自Kangax的代码很好。但是,当我将它合并到我的页面时,它没有。我认为这肯定是一个明显的错误。任何帮助都会非常感激!

////Detect whether position:fixed works (mobile browsers). Use JS to position #navwrap if not.
  //Kangax's script - begins at "function" on the next line.
function detected() {
    var container = document.body;
    if (document.createElement &&
    container && container.appendChild && container.removeChild) {
        var el = document.createElement("div");
        if (!el.getBoundingClientRect) {
            return null;
        }
        el.innerHTML = "x";
        el.style.cssText = "position:fixed;top:100px;";
        container.appendChild(el);
        var originalHeight = container.style.height, originalScrollTop = container.scrollTop;
        container.style.height = "3000px";
        container.scrollTop = 500;
        var elementTop = el.getBoundingClientRect().top;
        container.style.height = originalHeight;
        var isSupported = elementTop === 100;
        container.removeChild(el);
        container.scrollTop = originalScrollTop;
        return isSupported;
    }
    return null;
};
if (detected()) {
    alert ('non-mobile');
}
    else {
        alert ('mobile');
    }

如果它有帮助,原始代码(尽可能剥离):

<body>
<h2>Position Fixed Test</h2>    

<script>    
(function(__global){
// make sure `window` resolves to a global object
var window = this;
var features = { };
features.IS_POSITION_FIXED_SUPPORTED = (features.__IS_POSITION_FIXED_SUPPORTED = function () {
var container = document.body;
if (document.createElement &&
  container && container.appendChild && container.removeChild) {
  var el = document.createElement("div");
  if (!el.getBoundingClientRect) {
      return null;
  }
  el.innerHTML = "x";
  el.style.cssText = "position:fixed;top:100px;";
  container.appendChild(el);
  var originalHeight = container.style.height, originalScrollTop = container.scrollTop;
  container.style.height = "3000px";
  container.scrollTop = 500;
  var elementTop = el.getBoundingClientRect().top;
  container.style.height = originalHeight;
  var isSupported = elementTop === 100;
  container.removeChild(el);
  container.scrollTop = originalScrollTop;
  return isSupported;
}
return null;
})();
__global.__features = features;
})(this);

(function(){
function detect() {
 for (var i=0; i<1; i++) {
  var testResult = __features['IS_POSITION_FIXED_SUPPORTED'];
  alert ( testResult );
  i++;
 }
};
detect(); 
})();
</script>

</body>

2 个答案:

答案 0 :(得分:1)

我猜你总是得到non-mobile。您正在检查detected是否存在未执行该功能。将JavaScript的结尾更改为

if (detected()) {
  alert ('non-mobile');
}
else {
    alert ('mobile');
}

是否有理由将您的函数创建为分配给变量的匿名函数,而不是命名函数,例如。

function detected(){
  // Function content.
}

答案 1 :(得分:0)

排序。感谢您的投入。

原来我的代码版本运行正常,但它必须放在页面的正文中。如果它在Head中,即使在DOM Ready调用中也没有。

现在必须找出原因!但至少代码可以工作。