HTML5中5个简单实用的API

2019-01-28 17:25:12王冬梅

无需多说,跟classList一样,简单实用

window.postMessage API

即使是IE8也对postMessage API支持多年了,postMessage API的功能是可以让你在两个浏览器窗口或iframe之间传递信息数据:

复制代码

// 从A域上的窗口或iframe,发送一条信息到B域中的窗口或ifame
var iframeWindow = document.getElementById("iframe").contentWindow;
iframeWindow.postMessage("来自第一个窗口的问候!");</p> <p>// 在第二个不同域上的窗口或iframe接收消息
window.addEventListener("message", function(event) {
// 检验域的合法性
if(event.origin == "https://www.jb51.net") {
// 输出日志信息
console.log(event.data);
// 反馈消息
event.source.postMessage("你也好吗!");
}
]);

消息体只能是字符串,但你可以用JSON.stringify和JSON.parse将消息转换成更有意义的数据体!

autofocus属性

autofocus属性能够让BUTTON, INPUT, 或 TEXTAREA元素在页面加载完成时自动成为页面焦点:

复制代码

<input autofocus="autofocus" />
<button autofocus="autofocus">Hi!</button>
<textarea autofocus="autofocus"></textarea>

在像谷歌搜索页面那样的有固定模式的地方,autofocus属性是最理想的一个功能。

浏览器对各个API的支持稍有不同,所以,在使用前先检查一下对这些特征的支持情况。再花点时间阅读一下各个API的详细说明,相信你会有更多的发现。