菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
46
0

兼容性常规检测

原创
05/13 14:22
阅读数 1104

引子

碰到检查支持 font-family 的疑问,一时想不出,查了资料后解惑。顺便在此对是否支持的检测方式,进行一些基本的归纳。

HTML 检测

浏览器并不会对 HTML 进行编译,而是直接解析并显示结果,并以宽松模式运行。即使用了错误的语法,浏览器通常都有内建规则来解析书写错误的标记,页面仍然可以显示出来。对于比较新的标签,大都会有对应的 JS 对象可以进行检测。

不支持脚本检测

<noscript> 元素中定义脚本未被执行时的替代内容。

<noscript>Your browser does not support JavaScript!</noscript>

CSS 检测

通过 style 对象

通过获取 style 对象的某个属性值是否为字符串来判断。

typeof document.body.style.width // string
typeof document.body.style.test // undefined

supports 方法

浏览器原生提供 CSS 对象里面有个 supports 方法,用来检测浏览器是否支持给定的 CSS 规则,返回布尔值。
需要注意的是 window.CSS 这个对象并不是所有浏览器都支持。

window.CSS.supports("display: flex") // true
window.CSS.supports("display: test") // false
window.CSS.supports("display", "flex") // true
window.CSS.supports("display", "test") // false

Modernizr 是一个检测是否支持 HTML5 和 CSS3 特性的库。

事件检测

可以创建一个元素对象,然后检查在该对象中,是否有对应的属性。

function isSupportEvent(eventName) {
  if (typeof eventName !== 'string') {
    console.log('Event name is not legal !');
    return;
  }
  var element = document.createElement('div');
  eventName = 'on' + eventName;
  var isSupport = Boolean(eventName in element);
  return isSupport;
}

浏览器模型对象检测

这类都在 window 对象上,直接获取进行判断。对于支持对象,但部分支持对象拥有的方法,类似方式进行判断。

function isSupportObject(objName) {
  if (typeof objName !== 'string') {
    console.log('Object name is not legal !');
    return;
  }
  return Boolean(window[objName]);
}

字体检测

检测字体的思路是:初始化一个字符串,设置通用字体,获取其渲染宽度,然后设置需要检测的字体,获取渲染的宽度,比较两个宽度,相同说明不支持,不同说明支持。类似思路的还有这种方式

function isSupportFontFamily(font) {
  if (typeof font !== 'string') {
    console.log('Font name is not legal !');
    return;
  }

  var width;
  var body = document.body;

  var container = document.createElement('span');
  container.innerHTML = Array(10).join('wi');
  container.style.cssText = [
    'position:absolute',
    'width:auto',
    'font-size:128px',
    'left:-99999px'
  ].join(' !important;');

  var getWidth = function (fontFamily) {
    container.style.fontFamily = fontFamily;
    body.appendChild(container);
    width = container.clientWidth;
    body.removeChild(container);

    return width;
  };

  var monoWidth  = getWidth('monospace');
  var serifWidth = getWidth('serif');
  var sansWidth  = getWidth('sans-serif');

  return monoWidth !== getWidth(font + ',monospace') || sansWidth !== getWidth(font + ',sans-serif') || serifWidth !== getWidth(font + ',serif');
}

参考资料

发表评论

0/200
46 点赞
0 评论
收藏