当谈到或读到 “HTML5” 相关话题时,一半的人都会感觉这玩意儿还跟独角兽一样,只能孤芳自赏。但这能怪我们么?我们看着基本 API 停滞很久了,连一个基本的特性 placeholder 都让我们等上好一会儿。尽管很多 HTML5 特性在许多现代浏览器中都有实现,但是很多开发者却没有意识到那些我们能用上的一些更小而有用的 API。此文将这些 API 暴漏出来,希望能鼓励你们去探索那些少为人知的 HTML5 API。
Element.classList
该 classList API提供了基本的Javascript 对 CSS 的控制,这在几年前就可用了:
02 | myElement.classList.add( "newClass" ); |
05 | myElement.classList.remove( "existingClass" ); |
08 | myElement.classList.contains( "oneClass" ); |
11 | myElement.classList.toggle( "anotherClass" ); |
阅读此文查看其它 classList 属性
ContextMenu API
新的 ContextMenu API 是很不错的:可以不用重新定义浏览器的Context Menu,新的ContextMenu API 能够让你轻松地添加选项到浏览器的Context Menu中。
01 | < section contextmenu = "mymenu" > |
08 | < menu type = "context" id = "mymenu" > |
09 | < menuitem label = "Refresh Post" onclick = "window.location.reload();" icon = "/images/refresh-icon.png" ></ menuitem > |
10 | < menu label = "Share on..." icon = "/images/share_icon.gif" > |
11 | < menuitem label = "Twitter" icon = "/images/twitter_icon.gif" onclick = "goTo('//twitter.com/intent/tweet?text=' + document.title + ': ' + window.location.href);" ></ menuitem > |
12 | < menuitem label = "Facebook" icon = "/images/facebook_icon16x16.gif" onclick = "goTo('//facebook.com/sharer/sharer.php?u=' + window.location.href);" ></ menuitem > |
注意在使用 JavaScript 创建菜单标示前先使那些需要的选项事件生效。
Element.dataset
该 dataset API 允许开发者获取或者设置 data- 属性值:
08 | var element = document.getElementById( "myDiv" ); |
11 | var id = element.dataset.id; |
14 | var customKey = element.dataset.myCustomKey; |
17 | element.dataset.myCustomKey = "Some other value" ; |
window.postMessage API
该 postMessage API 已经在IE8中支持了几年,允许在windows和iframe元素之间传送message。
02 | var iframeWindow = document.getElementById( "iframe" ).contentWindow; |
03 | iframeWindow.postMessage( "Hello from the first window!" ); |
06 | window.addEventListener( "message" , function (event) { |
08 | if (event.origin == "http://davidwalsh.name" ) { |
10 | console.log(event.data); |
13 | event.source.postMessage( "Hello back!" ); |
Message 可能只是一些字符串,但是你可以使用JSON.stringify 和 JSON.parse 获取更多有用的数据。
autofocus 属性
autofocus 属性能确保给定的 BUTTON,INPUT,TEXTAREA 元素能够在页面加载完毕后获得焦点。
1 | < input autofocus = "autofocus" /> |
2 | < button autofocus = "autofocus" >Hi!</ button > |
3 | < textarea autofocus = "autofocus" ></ textarea > |
转自:http://www.oschina.net/question/89964_72242?from=20121014