Home > Article > Web Front-end > Sample code sharing for commonly used HTML5/CSS3 new feature capability detection methods
There will be more and more scenes using H5 in the future, which is something that makes web developers happy. However, there is a reality that we have to see clearly, that is, the IE series browsers still occupy a large part of the market share, mainly IE8 and 9, and users of Windows 8.1 have already used IE10/11. Considering our country’s national conditions, IE6 and 7 still have a lot of them left. When we let go of HTML5 development, new feature support testing is essential. One way is to use navigator.userAgent or navigator.appName to detect the browser type and version. However, this method is not very reliable. Browsers are gradually supporting some new features. It cannot be said with certainty that a certain browser supports 100% of them. HTML5. Moreover, IE11 made a disgusting move: removed the "MSIE" flag in UA, changed the appName to "Netspace", and began to support the -webkit-prefixed css attribute. This is a living disguise. Into the rhythm of chrome. Therefore, it is better to rely on feature detection (figure detection) or capability detection to detect HTML5/CSS3 support. This article will introduce what are the commonly used detection methods.
Supplement: This method can still be used to determine IE11: /Trident/i.test(navigator.appVersion), get from mustache.
The main methods for detecting new features of HTML5 are as follows:
1. Check whether there are any global objects (window or navigator) There is no corresponding attribute name
2. Create an element, check whether there is a corresponding attribute on the element
3. Create an element, check whether there is a method name on the element, and then call the method, See if it can be executed correctly
4. Create an element, assign a value to the corresponding attribute of the element, and then get the value of this attribute to see if the assignment takes effect
Due to different browsers For different behaviors, when detecting some features, a combination of the above methods may be used. Next, use the above methods to detect common features:
function support_canvas(){ var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); }
Generally speaking, just create the canvas element and check the getContext attribute, but it is not accurate enough in some browsers, so you can be completely sure by checking the execution result of elem.getContext('2d').
Regarding canvas, one thing to add is the fillText method. Although the browser supports canvas, we are not sure that it supports the fillText method because canvas API has experienced various Modification, there are some historical reasons, the method to detect support for fillText is as follows:
function support_canvas_text(){ var elem = document.createElement('canvas'); var context = elem.getContext('2d'); return typeof context.fillText === 'function'; }
function support_video(){ return !!document.createElement('video').canPlayType; }function support_audio(){ return !!document.createElement('audio').canPlayType; }
Video and audio are written similarly.
To detect the resource format supported by video/audio, you can call the canPlayType method to check, as follows:
unction support_video_ogg(){ var elem = document.createElement('video'); return elem.canPlayType('video/ogg; codecs="theora"'); }function support_video_h264(){ var elem = document.createElement('video'); return elem.canPlayType('video/mp4; codecs="avc1.42E01E"'); }function support_video_webm(){ var elem = document.createElement('video'); return elem.canPlayType('video/webm; codecs="vp8, vorbis"'); }function support_audio_ogg(){ var elem = document.createElement('audio'); return elem.canPlayType('audio/ogg; codecs="vorbis"'); }function support_audio_mp3(){ var elem = document.createElement('audio'); return elem.canPlayType('audio/mpeg;'); }function support_audio_wav(){ var elem = document.createElement('wav'); return elem.canPlayType('audio/wav; codecs="1"'); }
It should be noted that the return value of canPlayType is not a Boolean type , but string , the values are as follows:
"probably": The browser fully supports this format
"maybe": The browser may support this format
"": empty string, indicating that it is not supported
Generally speaking, just check whether the global object has a localStorage attribute, as follows:
function support_localStorage(){ try { return 'localStorage' in window && window['localStorage'] !== null; } catch(e){ return false; } }
In some browsers, cookie is disabled, or privacy mode is set. , check attributes or report an error, so add it to the try statement. If an error is reported, it is considered not supported.
In addition, there is a more strict checking method to check whether the corresponding method is supported, as follows:
function support_localStorage(){ try { if('localStorage' in window && window['localStorage'] !== null){ localStorage.setItem('test_str', 'test_str'); localStorage.removeItem('test_str'); return true; } return false; } catch(e){ return false; } }
function support_webWorker(){ return !!window.Worker; }
function support_applicationCache(){ return !!window.applicationCache; }
function support_geolocation(){ return 'geolocation' in navigator; }
The new attributes of the input tag include: autocomplete, autofocus, list, placeholder, max, min, multiple, pattern, required, step, To check whether method 2 mentioned above is supported, create a new input tag and see if it has these attributes. Take autocomplete as an example:
function support_input_autocomplete(){ var elem = document.createElement('input'); return 'autocomplete' in elem; }
In addition, pay special attention to the list attribute because it is used in conjunction with the datalist tag. , so when checking, you must also check whether the datalist tag supports:
function support_input_list(){ var elem = document.createElement('input'); return !!('list' in elem && document.createElement('datalist') && window.HTMLDataListElement); }
The type here refers to the value of type, and the new type value of input includes: search, tel, url, email, datetime, date, month, week, time, datetime-local, number, range, color. To detect these values, you need to use method 4 mentioned above, taking number as an example:
function support_input_type_number(){ var elem = document.createElement('input'); elem.setAttribute('type', 'number'); return elem.type !== 'text'; }
这是一种较为简单的检查方法,因为严格来讲,浏览器会为不同的类型提供不同的外观或实现,例如chrome中range类型会长这样:
我们要确切的知道浏览器为该类型提供了对应的实现,才可以认为是“支持的”,要从这个方面检测是有难度的,各浏览器实现都不一。下面贴出Modernizr中的一个实现,供参考:检测email类型的实现:
function support_input_type_email(){ var elem = document.createElement('input'); elem.setAttribute('type', 'email'); elem.value = ':)'; return elem.checkValidity && elem.checkValidity() === false; }
为email类型设置了一个非法的value,然后手动调用校验方法,如果返回false,说明浏览器提供了该类型的实现,认为是支持的。
history虽说是HTML4就有的,但HTML5提供了新的方法,检测方法如下:
function support_history(){ return !!(window.history && history.pushState); }
function support_webgl(){ return !!window.WebGLRenderingContext; }
function support_postMessage(){ return !!window.postMessage; }
HTML5的拖拽特性:
function support_draggable(){ var p = document.createElement('p'); return ('draggable' in p) || ('ondragstart' in p && 'ondrop' in p); }
unction support_webSocket(){ return 'WebSocket' in window || 'MozWebSocket' in window; }
function support_svg(){ return !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect; }
检查事件的支持性,用上面提到的方法2就可以,创建一个元素,看元素上有没有对应的事件名称,下面是摘自Modernizr的实现:
isEventSupported = (function() { var TAGNAMES = { 'select': 'input', 'change': 'input', 'submit': 'form', 'reset': 'form', 'error': 'img', 'load': 'img', 'abort': 'img' }; function isEventSupported( eventName, element ) { element = element || document.createElement(TAGNAMES[eventName] || 'div'); eventName = 'on' + eventName; // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those var isSupported = eventName in element; if ( !isSupported ) { // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element if ( !element.setAttribute ) { element = document.createElement('div'); } if ( element.setAttribute && element.removeAttribute ) { element.setAttribute(eventName, ''); isSupported = is(element[eventName], 'function'); // If property was created, "remove it" (by setting value to `undefined`) if ( !is(element[eventName], 'undefined') ) { element[eventName] = undefined; } element.removeAttribute(eventName); } } element = null; return isSupported; } return isEventSupported; })()
View Code
如果仅仅是检查touch事件是否支持,就没必要写上面那么多东西了,可以简单书写如下:
function support_touch_event(){ return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch); }
Mozilla还提供了一个媒体查询的语句用来检测touch的支持性:touch-enabled,可以在页面上插入一个带有此媒体查询的元素来判断是否支持touch事件
不过我们做移动开发一般都只考虑webkit内核了,Mozilla的方式就不写了,如果需要请参考Modernizr源码。
css3属性支持度的检测,主要通过上面方法提到的2和4来检查,不过我们要检查的是元素的style属性。另外一个要提的就是浏览器私有前缀,在现阶段我们用css3属性大部分是要写前缀的,因为各浏览器还未完全支持。我们用到的前缀有:-webkit-、-ms-、-o-、-moz-,至于前缀-khtml-,这是Safari早期使用的,现在基本也没有人再用它了,所以进行检测的时候就把它省去了。Modernizr移除了此前缀的检测,
通用代码如下:
var support_css3 = (function() { var div = document.createElement('div'), vendors = 'Ms O Moz Webkit'.split(' '), len = vendors.length; return function(prop) { if ( prop in div.style ) return true; prop = prop.replace(/^[a-z]/, function(val) { return val.toUpperCase(); }); while(len--) { if ( vendors[len] + prop in div.style ) { return true; } } return false; }; })();
View Code
css3 3D变形的检测稍微复杂些,首先要支持perspective属性,其次要支持transform-style的值为preserve-3d。用方法4的方式无法检测出来,需要借助媒体查询的方式,代码如下:
function support_css3_3d(){ var docElement = document.documentElement; var support = support_css3('perspective'); var body = document.body; if(support && 'webkitPerspective' in docElement.style){ var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '@media (transform-3d),(-webkit-transform-3d){#css3_3d_test{left:9px;position:absolute;height:3px;}}'; body.appendChild(style); var div = document.createElement('div'); div.id = 'css3_3d_test'; body.appendChild(div); support = div.offsetLeft === 9 && div.offsetHeight === 3; } return support; }
需要借助上面定义好的support_css3方法来检测perspective。
基本常用检测的就这些了,本文中一部分代码是网上搜来的,还有一部分是从Modernizr源码中抽离出来的。如文中叙述有误,欢迎指正。
在实际开发中,推荐直接使用Modernizr进行检测,它已经封装的非常漂亮了。但是如果你仅仅检测几个属性,或者不想因加载额外的库而浪费性能,就可以使用上述代码进行单个检测。
先写这么多,以后有想到的再进行补充。
The above is the detailed content of Sample code sharing for commonly used HTML5/CSS3 new feature capability detection methods. For more information, please follow other related articles on the PHP Chinese website!