search
HomeWeb Front-endH5 TutorialSample 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.

HTML5 part

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:

canvas

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';
}

video/audio

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

localStorage

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;
    }
}

webWorker

function support_webWorker(){    
return !!window.Worker;
}

applicationCache

function support_applicationCache(){    
return !!window.applicationCache;
}

geolocation

function support_geolocation(){    
return 'geolocation' in navigator;
}

input tagNew attributes

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);
}

input tag new type

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

  history虽说是HTML4就有的,但HTML5提供了新的方法,检测方法如下:

function support_history(){    return !!(window.history && history.pushState);
}

webgl

function support_webgl(){    return !!window.WebGLRenderingContext;
}

postMessage

function support_postMessage(){    return !!window.postMessage;
}

draggable

HTML5的拖拽特性:

function support_draggable(){    
var p = document.createElement('p');    
return ('draggable' in p) || ('ondragstart' in p && 'ondrop' in p);
}

webSocket

unction support_webSocket(){    
return 'WebSocket' in window || 'MozWebSocket' in window;
}

svg

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事件

  如果仅仅是检查touch事件是否支持,就没必要写上面那么多东西了,可以简单书写如下:

function support_touch_event(){    
return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
}

  Mozilla还提供了一个媒体查询的语句用来检测touch的支持性:touch-enabled,可以在页面上插入一个带有此媒体查询的元素来判断是否支持touch事件

  不过我们做移动开发一般都只考虑webkit内核了,Mozilla的方式就不写了,如果需要请参考Modernizr源码。

css3部分

通用方法

  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

3D变形

  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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment