Home >Web Front-end >H5 Tutorial >Detailed introduction to browser support for new features of code detection HTML5/CSS3
With the release of the HTML5 standard version at the end of October this year, there will be more and more scenes using HTML5 in the future, which is something that web developers are excited about. 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: it removed the "MSIE" mark in UA, changed the appName to "Netspace", and began to support the -webkit- prefixed CSS attribute. This is a rhythm disguised as 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.
The main methods for detecting new features of HTML5 are as follows:
1. Check whether there is a corresponding attribute name on the global object (window or navigator)
2. Create an element and check whether there are corresponding attributes on the element
3. Create an element, check whether there is a method name on the element, and then call the method to 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 the different behaviors of different browsers, detect some characteristics When doing this, a combination of the above methods may be used. Next, use the above method 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'). The above code is taken from Modernizr: http://www.php.cn/
Regarding canvas, one thing to add is the fillText method. Although the browser supports canvas, we are not sure that it supports fillText. Method, because the canvas API has gone through various modifications, 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; }
The writing methods of video and audio are similar.
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 a 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; } }
Disable cookies in some browsers, or set When privacy mode or something is disabled, properties are checked or an error is reported, so it is added 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. Check whether the above mentioned attributes are supported. Method 2 is enough. 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 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); }
Here Type refers to the value of type. The new type values added to input include: search, tel, url, email, datetime, date, month, week, time, datetime-local, number, range, and 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'; }
This is a relatively simple checking method, because strictly speaking , the browser will provide different appearances or implementations for different types. For example, the range type in chrome will look like this:
We need to know exactly what the browser provides for this type. Only when the corresponding implementation is provided can it be considered "supported". It is difficult to detect from this aspect, as each browser has different implementations. An implementation in Modernizr is posted below for reference: Implementation of detecting email type:
function support_input_type_email(){ var elem = document.createElement('input'); elem.setAttribute('type', 'email'); elem.value = ':)'; return elem.checkValidity && elem.checkValidity() === false; }
sets an illegal value for the email type, and then calls it manually Verification method, if it returns false, it means that the browser provides an implementation of this type and is considered to be supported.
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] || 'p'); 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('p'); } 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; })()
如果仅仅是检查touch事件是否支持,就没必要写上面那么多东西了,可以简单书写如下:
function support_touch_event(){ return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch); }
Mozilla还提供了一个媒体查询的语句用来检测touch的支持性:touch-enabled,可以在页面上插入一个带有此媒体查询的元素来判断是否支持touch事件。参考:http://www.php.cn/
不过我们做移动开发一般都只考虑webkit内核了,Mozilla的方式就不写了,如果需要请参考Modernizr源码。
css3属性支持度的检测,主要通过上面方法提到的2和4来检查,不过我们要检查的是元素的style属性。另外一个要提的就是浏览器私有前缀,在现阶段我们用css3属性大部分是要写前缀的,因为各浏览器还未完全支持。我们用到的前缀有:-webkit-、-ms-、-o-、-moz-,至于前缀-khtml-,这是Safari早期使用的,现在基本也没有人再用它了,所以进行检测的时候就把它省去了。Modernizr移除了此前缀的检测,详见:http://www.php.cn/
通用代码如下:
var support_css3 = (function() { var p = document.createElement('p'), vendors = 'Ms O Moz Webkit'.split(' '), len = vendors.length; return function(prop) { if ( prop in p.style ) return true; prop = prop.replace(/^[a-z]/, function(val) { return val.toUpperCase(); }); while(len--) { if ( vendors[len] + prop in p.style ) { return true; } } return false; }; })();
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 p = document.createElement('p'); p.id = 'css3_3d_test'; body.appendChild(p); support = p.offsetLeft === 9 && p.offsetHeight === 3; } return support; }
需要借助上面定义好的support_css3方法来检测perspective。
基本常用检测的就这些了,本文中一部分代码是网上搜来的,还有一部分是从Modernizr源码中抽离出来的。如文中叙述有误,欢迎指正。
在实际开发中,推荐直接使用Modernizr进行检测,它已经封装的非常漂亮了。但是如果你仅仅检测几个属性,或者不想因加载额外的库而浪费性能,就可以使用上述代码进行单个检测
The above is the detailed content of Detailed introduction to browser support for new features of code detection HTML5/CSS3. For more information, please follow other related articles on the PHP Chinese website!