使用modernizr.js检测浏览器对html5以及css3的支持情况

737 查看

使用modernizr.js检测浏览器对html5和css3的支持情况

详情请看主页:modernizr主页

1. modernizr 是什么?

modernize 是一个js库————一个用于检测当前浏览器对html5&css3 的支持情况,其中包括对 css3 @font-face、border-radius、 border-image、box-shadow、rgba() 的支持检测,以及 html5 audio、video、localStorage、sessionStorage 等的支持情况。

2. 如何使用它?

使用非常简单,只需要在官网下载 modernize.js 文件,并在页面的 head 标签中引用:

    <!DOCTYPE html>  
    <html>  
    <head>  	
    <meta charset="utf-8">  	
    <title>It's just a test for modernizr.js by alexchen</title>  	
    <script src="modernizr-1.5.min.js"></script>  
    </head>
    

接着在 html 标签中加入 class='nojs' 类:

    
    <html class="no-js">
    

就可以了。
加载页面之后你会看到 html 标签的 class 中多出了很多类,像下面这样:


    <html class=" js flexbox canvas canvastext webgl no-touch geolocation postmessage no-websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients no-cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths">
    
    <head>
        <title></title>
        <script src="modernizr.js"></script>
    </head>
    
    <body>

class 中列出了所有当前浏览器支持的 html5&css3 的一些特性,如果是不支持的,则会在 class 中显示一个以 no- 开头的类,比如不支持 canvas 则会有一个 no-canvas 的类,比如在 ie8 下面,则会得到如下类,并且会为我们生成一些默认的样式:

    <HTML class=" js no-flexbox no-canvas no-canvastext no-webgl no-touch no-geolocation postmessage no-websqldatabase no-indexeddb hashchange no-history draganddrop no-websockets no-rgba no-hsla no-multiplebgs no-backgroundsize no-borderimage no-borderradius no-boxshadow no-textshadow no-opacity no-cssanimations no-csscolumns no-cssgradients no-cssreflections no-csstransforms no-csstransforms3d no-csstransitions fontface generatedcontent no-video no-audio no-localstorage no-sessionstorage no-webworkers no-applicationcache no-svg no-inlinesvg no-smil no-svgclippaths"><HEAD>
    <STYLE>article {
    	DISPLAY: block
    }
    aside {
    	DISPLAY: block
    }
    dialog {
    	DISPLAY: block
    }
    figcaption {
    	DISPLAY: block
    }
    figure {
    	DISPLAY: block
    }
    footer {
    	DISPLAY: block
    }
    header {
    	DISPLAY: block
    }
    hgroup {
    	DISPLAY: block
    }
    main {
    	DISPLAY: block
    }
    nav {
    	DISPLAY: block
    }
    section {
    	DISPLAY: block
    }
    mark {
    	BACKGROUND: #ff0; COLOR: #000
    }
    template {
    	DISPLAY: none
    }
    </STYLE>
    <TITLE></TITLE>
    <SCRIPT src="modernizr.js"></SCRIPT>
    </HEAD>
    <BODY></BODY></HTML>
    

因此,当检测到浏览器不支持某些 h5和css3 的特性时,我们就需要编写额外的处理代码来让页面实现 平稳退化 。同时, modernizr.js 还会为我们创建一个全局对象 Modernizr ,通过访问属性的方式我们可以获取某特性是否支持,如果支持则返回 true 反之则为 false ,看个栗子,在 ie8 中,不支持 canvas ,因此对应的类为 no-canvas ,我们也可以通过 Modernizr 对象来获取,代码如下:

>>Modernizr.canvas
>>false

根据检测结果我们就可以对某些特性的特出处理来达到 平稳退化 的效果