移动Web开发,4行代码检测浏览器是否支持position:fixed

10 篇文章 0 订阅
var div = document.createElement('div');
div.style.cssText = 'display:none;position:fixed;z-index:100;';
body.appendChild(div);
console.log(window.getComputedStyle(div).position != 'fixed');


对于不支持fixed的浏览器,`window.getComputedStyle(div).position`计算出来的值会是`absolute`。

在这段代码的基础上,可以封装一个公共函数,并将已知的不支持fixed浏览器直接过滤掉。
 

function isSupportFixed() {
    var userAgent = window.navigator.userAgent, 
        ios = userAgent.match(/(iPad|iPhone|iPod)\s+OS\s([\d_\.]+)/),
        ios5below = ios && ios[2] && (parseInt(ios[2].replace(/_/g, '.'), 10) < 5),
        operaMini = /Opera Mini/i.test(userAgent),
        body = document.body,
        div, isFixed;

    div = document.createElement('div');
    div.style.cssText = 'display:none;position:fixed;z-index:100;';
    body.appendChild(div);
    isFixed = window.getComputedStyle(div).position != 'fixed';
    body.removeChild(div);
    div = null;

    return !!(isFixed || ios5below || operaMini);
}

如果不写z-index,浏览器在计算样式时,会将fixed计算成static

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值