在使用jQuery的keyup、keydown、keypress等鍵盤事件時,可能會遇到一個惱人的瀏覽器差異:某些元素在獲得焦點後,會出現一圈討厭的虛線焦點框,尤其是在IE裡,即使加上tabIndex也難以消除。下面這段代碼透過重寫jQuery的鍵盤事件方法,在綁定事件時自動為元素補上tabIndex、去除虛線輪廓,讓鍵盤操作體驗更乾淨。
代碼如下:
(function($){
var no_ie_pr = function(e){
var _this = e;
var tabpr = function(e){
_this.attr('tabIndex', 1).click(function(){
_this.focus();
});
if(!$.browser.msie){
_this.css("outline-style", "none");
}
}
var gettag = _this[0].tagName.toLowerCase();
var oe = ['abbr','acronym','address','b','bdo','big','blockquote','center','cite','dd','del','dir','dfn','dl','dt','em','font','form','h1','h2','h3','h4','h5','h6','i','ins','img','ins','kbd','li','menu','ol','p','pre','q','s','samp','small','strike','strong','sub','sup','th','tr','tt','u','ul','var'];
if($.inArray(gettag, oe)!=-1){
tabpr();
}else{
if ($.browser.msie) {
var ce = ['span','div'];
if($.inArray(gettag, ce)!=-1){
//IE只對絕對定位元素和固定定位元素有效,加tabIndex無法消除虛線
}else{
var ce = ['label','legend','tbody','tfoot','thead'];
if($.inArray(gettag, ce)!=-1){
tabpr();
}
}
}else{
var ce = ['caption','fieldset','table','td','code','div','span','label','legend','tbody','tfoot','thead'];
if($.inArray(gettag, ce)!=-1){
tabpr();
}
}
}
}
$.fn.oldKeyup = $.fn.keyup;
$.fn.keyup = function(fn){
no_ie_pr(this);
$(this).oldKeyup(fn);
}
$.fn.oldKeypress = $.fn.keypress;
$.fn.keypress = function(fn){
no_ie_pr(this);
$(this).oldKeypress(fn);
}
$.fn.oldKeydown = $.fn.keydown;
$.fn.keydown = function(fn){
no_ie_pr(this);
$(this).oldKeydown(fn);
}
})(jQuery)
這段代碼的運作思路是:先把jQuery原生的keyup、keypress、keydown三個方法各保存一份備份,再重新定義它們。每次調用這些鍵盤事件方法時,都會先執行no_ie_pr(),根據元素的標簽類型判斷是否需要處理焦點虛線,然後再呼叫原始方法完成事件綁定。對於非IE瀏覽器,直接透過css("outline-style", "none")去掉輪廓線;而IE因為對span、div這類元素加tabIndex仍無法消除虛線,所以特別做了區分處理。