使用modernizr.js檢測瀏覽器對html5以及css3的支持狀況

使用modernizr.js檢測瀏覽器對html5和css3的支持狀況

詳情請看主頁:modernizr主頁css

1. modernizr 是什麼?

modernize 是一個js庫————一個用於檢測當前瀏覽器對html5&css3 的支持狀況,其中包括對 css3 @font-face、border-radius、 border-image、box-shadow、rgba() 的支持檢測,以及 html5 audio、video、localStorage、sessionStorage 等的支持狀況。html

2. 如何使用它?

使用很是簡單,只須要在官網下載 modernize.js 文件,並在頁面的 head 標籤中引用:html5

<!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' 類:css3

<html class="no-js">

就能夠了。
加載頁面以後你會看到 html 標籤的 class 中多出了不少類,像下面這樣:web

<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 下面,則會獲得以下類,而且會爲咱們生成一些默認的樣式:sql

<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 對象來獲取,代碼以下:canvas

>>Modernizr.canvas
>>false

根據檢測結果咱們就能夠對某些特性的特出處理來達到 平穩退化 的效果瀏覽器

相關文章
相關標籤/搜索