HTML5的语义化标签以及属性,可以让开发者非常方便地实现清晰的web页面布局,加上CSS3的效果渲染,快速建立丰富灵活的web页面显得非常简单。
HTML5的新标签元素有:
header
定义页面或区段的头部;
footer
定义页面或区段的尾部;
nav
定义页面或区段的导航区域;
section
页面的逻辑区域或内容组合;
article
定义正文或一篇完整的内容;
aside
定义补充或相关内容;
使用他们能让代码语义化更直观,而且更方便SEO优化。但是此HTML5新标签在IE6/IE7/IE8上并不能识别,需要进行JavaScript处理。以下就介绍几种方式。
方式一:
Coding JavaScript
<!--[if lt IE9]>
<script>
(function() {
if (!
/*@cc_on!@*/
0) return;
var e = "abbr, article, aside, audio, canvas, datalist, details, dialog, eventsource, figure, footer, header, hgroup, mark, menu, meter, nav, output, progress, section, time, video".split(', ');
var i= e.length;
while (i--){
document.createElement(e[i])
}
})()
</script>
<![endif]-->
如果是IE9以下的IE浏览器将创建HTML5标签, 这样非IE浏览器就会忽视这段代码,也就不会有无谓的http请求了。
第二种方法:
使用Google的html5shiv包(推荐)
.example-gradient {
background: -webkit-linear-gradient(left, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* Chrome10+, Safari5.1+ */
background: -moz-linear-gradient(left, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* FF3.6+ */
background: -ms-linear-gradient(left, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* IE10+ */
background: -o-linear-gradient(left, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* Opera 11.10+ */
background: linear-gradient(to right, #cb60b3 0%, #c146a1 50%, #a80077 51%, #db36a4 100%); /* W3C */
}
.example-angle {
transform: rotate(10deg);
}
.example-color {
color: rgba(255, 0, 0, 0.2);
background: purple;
border: 1px solid hsl(100, 70%, 40%);
}
.example-easing {
transition-timing-function: linear;
}
.example-time {
transition-duration: 3s;
}
span.foo {
background-color:
navy;
color:
#BFD;
}
span.bar {
background:
rgba(105, 0, 12, .38);
color:
hsl(30, 100%, 50%);
border-color:
transparent;
}
<!--[if lt IE9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
由于国内google的服务器访问卡,建议调用国内的cdn
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<![endif]-->
但是不管使用以上哪种方法,都要初始化新标签的CSS.因为HTML5在默认情况下表现为内联元素,对这些元素进行布局我们需要利用CSS手工把它们转为块状元素方便布局
复制代码代码如下:
article,aside,dialog,footer,header,section,footer,nav,figure,menu{
display:block
}
但是如果ie6/7/8 禁用脚本的用户,那么就变成了无样式的"白板"网页,我们该怎么解决呢?
我们可以参照facebook的做法,即引导用户进入带有noscript标识的 “/?_fb_noscript=1”页面,用 html4 标签替换 html5 标签,这要比为了保持兼容性而写大量 hack 的做法更轻便一些。
<!--[if lte IE 8]>
<noscript>
<style>.html5-wrappers{display:none!important;}</style>
<div class="ie-noscript-warning">您的浏览器禁用了脚本,请<a href="">查看这里</a>来启用脚本!或者<a href="/?noscript=1">继续访问</a>.
</div>
</noscript>
<![endif]-->
这样可以引导用户开启脚本,或者直接跳转到HTML4标签设计的界面。
好了使用HTML5Shiv完美解决IE(IE6/IE7/IE8)不兼容HTML5标签的几种方法已经分享完毕,如有补充欢迎加群讨论