DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> WEB網站前端 >> 前端技巧 >> html5中幾個不容錯過的api或者tips小結
html5中幾個不容錯過的api或者tips小結
編輯:前端技巧     
之前的博文中,一直有關注一些HTML 5中的值得關注但少用的API或者tips,這次繼續小結一些。
1)element.classList
詳細的可以參考
https://developer.mozilla.org/en-US/docs/DOM/element.classList
這裡簡單說下,它其實是一個快速對某個元素的class進行操作的新的DOM API了,比如
包括了add,remove,toggle,contains的方法,比如
myDiv.classList.add('myCssClass');
myDiv.classList.remove('myCssClass');
myDiv.classList.toggle('myCssClass'); //now it's added
myDiv.classList.toggle('myCssClass'); //now it's removed
myDiv.classList.contains('myCssClass'); //returns true or false
現在的浏覽器支持情況為:
chrome 8.0+,ie 10,opera 11.5,safari 5.1
2)ContextMenu 上下文菜單 API
這個API是HTML 5的,用來可以生成簡單的可以點擊的上下文菜單,能給用戶快速的選擇和顯示,比如

復制代碼代碼如下:
<section contextmenu="mymenu">
<!--
For the purpose of cleanliness,
I'll put my menu inside the element that will use it
-->
<!-- add the menu -->
<menu type="context" id="mymenu">
<menuitem label="Refresh Post" onclick="window.location.reload();" icon="/images/refresh-icon.png"></menuitem>
<menu label="Share on..." icon="/images/share_icon.gif">
<menuitem label="Twitter" icon="/images/twitter_icon.gif" onclick="goTo('//twitter.com/intent/tweet?text=' + document.title + ': ' + window.location.href);"></menuitem>
<menuitem label="Facebook" icon="/images/facebook_icon16x16.gif" onclick="goTo('//facebook.com/sharer/sharer.php?u=' + window.location.href);"></menuitem>
</menu>
</menu>
</section>

3)element.dataset
這個API用來獲得鍵值對的時候很有用:
比如:

復制代碼代碼如下:
<div id="myDiv" data-name="myDiv" data-id="myId" data-my-custom-key="This is the value"></div>

則通過下面這些可以獲得鍵值對,這個用在jquery mobile中很實用:

復制代碼代碼如下:
// 獲得元素
var element = document.getElementById("myDiv");
// 獲得id
var id = element.dataset.id;
// 獲得data-my-custom-key"
var customKey = element.dataset.myCustomKey;
// 設置新的值
element.dataset.myCustomKey = "Some other value";

4)postMessage API
這個居然在IE 8後就支持了,可以支持在不同domain的iframe中傳遞消息

復制代碼代碼如下:
// From window or frame on domain 1, send a message to the iframe which hosts another domain
var iframeWindow = document.getElementById("iframe").contentWindow;
iframeWindow.postMessage("Hello from the first window!");
// From inside the iframe on different host, receive message
window.addEventListener("message", function(event) {
if(event.origin == "http://davidwalsh.name") {
// Log out the message
console.log(event.data);
// Send a message back
event.source.postMessage("Hello back!");
}
]);

5)autofocus
這個很簡單了,自動focus到控件

復制代碼代碼如下:
<input autofocus="autofocus" />
<button autofocus="autofocus">Hi!</button>
<textarea autofocus="autofocus"></textarea>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved