您当前的位置:首页 > 计算机 > 编程开发 > Html+Div+Css(前端)

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

时间:12-14来源:作者:点击数:

不废话,直接上代码

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

在这段代码的基础上,可以封装一个公共函数,并将已知的不支持 position: 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);
}
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐