Bạn có thể đính kèm focus
và blur
trình xử lý sự kiện vào đối tượng window
để theo dõi xem cửa sổ bị mất hay mất tiêu điểm (xem http://jsfiddle.net/whQFz/ cho ví dụ nhỏ). window
áp dụng cho ngữ cảnh trình duyệt hiện tại (để có thể là cửa sổ, tab, khung, v.v.).
Lưu ý: Sự kiện focus
sẽ kích hoạt mỗi khi cửa sổ lấy nét và sự kiện blur
sẽ kích hoạt mỗi lần mất tiêu điểm. Một ví dụ về thứ gì đó lấy nét ra khỏi cửa sổ là một cửa sổ alert
. Nếu bạn cố gắng cảnh báo trong trình xử lý sự kiện onfocus
, bạn sẽ nhận được một chuỗi thông báo vô hạn!
// Set global counter variable to verify event instances
var nCounter = 0;
// Set up event handler to produce text for the window focus event
window.addEventListener("focus", function(event)
{
document.getElementById('message').innerHTML = "window has focus " + nIndex;
nCounter = nCounter + 1;
}, false);
// Example of the blur event as opposed to focus
// window.addEventListener("blur", function(event) {
// document.getElementById('message').innerHTML = "window lost focus"; },
// false);
Nguồn
2010-08-13 16:16:13
Làm thế nào là nó có khả năng tương thích trình duyệt? –