此前我一直在留意 HTML5 中那些實用但使用率不高的 API 與技巧,這次再補充幾個。
詳細文檔可參考 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
它最大的價值在於免去了字串拼接與正則判斷,過去判斷「有沒有這個 class」得寫 className.indexOf,現在一句 contains 就夠了。瀏覽器支持情況:Chrome 8.0+、IE 10、Opera 11.5、Safari 5.1。
這是 HTML5 提供的 API,用於生成可點擊的自定義右鍵菜單,讓用戶快速執行常用操作:
<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>
需要注意,這個 API 目前僅 Firefox 完整支持,Chrome 已移除了對應實現,因此不適合作為關鍵功能的依賴。
讀取 data-* 自定義屬性時非常方便。比如:
<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";
注意命名轉換規則:data-my-custom-key 在 JS 中會變成 myCustomKey,反之賦值時駝峰命名也會被序列化為短橫線形式。
這個 API 從 IE8 之後就已支持,可用於在不同域的 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 == "https://davidwalsh.name") {
// Log out the message
console.log(event.data);
// Send a message back
event.source.postMessage("Hello back!");
}
});
實戰中務必校驗 event.origin,並在發送時顯式指定 targetOrigin,不要用星號通配,否則等於把消息廣播給任意嵌入方。
讓控件在頁面加載後自動獲得焦點,一個屬性即可:
<input autofocus="autofocus" />
<button autofocus="autofocus">Hi!</button>
<textarea autofocus="autofocus"></textarea>
使用時有兩點要留意:同一頁面只應有一處 autofocus,否則行為由瀏覽器自行決定;另外它會干擾屏幕閱讀器的朗讀順序,出於無障礙考慮,移動端頁面最好避免使用。