我有JavaScript代碼監聽按下「返回」鍵,
作品在所有瀏覽器,除了WebKit瀏覽器。
我知道webkit最近changes to keyboard event handling。
我找不到合適的解決方案 in this detailed explanation。觸發鍵盤事件,WebKit的鍵盤不會觸發事件
這裏是code。
function addEventHandler(node,type,fn){
if(typeof window.event !== "undefined"){
/* Internet Explorer way */
node.attachEvent("on" + type, fn);
} else {
/* FF & Other Browsers */
node.addEventListener(type, fn,false);
}
}
function detectSubmit(){
searchTextInput = document.getElementById("txtSearch")
addEventHandler(searchTextInput,"keydown",triggerSearch);
}
function triggerSearch(e){
//getting the character that was pressed cross browser.
var key = e.keycode ? e.keycode : e.which;
//detect if the return key was pressed.
if(key==13){
alert("return clicked");
}
}
addEventHandler(window,"load",detectSubmit);
爲什麼不使用jQuery等javascript庫以最少的代碼自動解決跨瀏覽器問題? – Sarfraz 2010-06-20 15:48:52
謝謝,我總是使用jQuery,但這是第三方網站的橫幅廣告。 – adardesign 2010-06-20 15:50:33