检测位置:用javascript固定

Detect position:fixed with javascript

本文关键字:javascript 固定 位置 检测      更新时间:2023-09-26

我正在尝试从这里使用Kangax的脚本:http://kangax.github.com/cft/检测那些像桌面浏览器一样"正确"实现position:fixed的浏览器,与移动浏览器相比,所以我可以使用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>

我猜你总是non-mobile.您正在检查detected是否存在,而不是执行该函数。将 JavaScript 的结尾更改为

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

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

function detected(){
  // Function content.
}

排序。感谢您的输入。

事实证明,我的代码版本运行良好,但它必须放在页面正文中。如果它在 Head 中,即使在 DOM Ready 调用中,它也不会。

现在必须找出原因!但至少代码有效。