作者contagious (漂移胖)
看板Ajax
标题Re: [心得]jQuery blur事件扩充
时间Fri Sep 19 05:46:13 2008
其实我完全没有这个需求...不过无聊就练习一下:
// jquery 1.2.6 引进了的自订事件的语法
// 我们要 overwrite blur 事件
$.event.special.blur = {
//当事件被注册的时候,会先呼叫这个 function
//此 function 中的 this 就是被注册事件的 element
setup: function() {
// 先判断此 element 是不是本来就可以 bind blur
// 这里我直接比对 tagName 是不是 input/select 之类的
var tag_name = this.tagName;
if(tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' ||
tag_name =='BUTTON' || tag_name == 'LABEL') {
return false; //回传 false 表示用预设的行为
}
//因为 js scope 的问题,先把 this 存在另一个变数中
var that = $(this);
// 为此 element 增加一个用来 proxy 事件的 input
if(!this.proxy_input){ //如果已经有这个 proxy input 了...就不用再生一次了
this.proxy_input = $('<input type="text" />'). // 生出来
addClass('proxy_input'). // 加上 class name
insertAfter(this). // 放到原本的 element 後面
focus(function() { that.focus(); }). // proxy focus event
blur( function() { that.blur(); }). // proxy blur event
css({ top: that.offset().top, // 将它的位置设成和原来一样
left: that.offset().left,
width: that.width(),
height: that.height() });
}
return true;
},
//当事件被取消的时候,会先呼叫这个 function
teardown: function() {
//同样先判断是不是原本就可以 bind blur 的 element
var tag_name = this.tagName;
if(tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' ||
tag_name =='BUTTON' || tag_name == 'LABEL') {
return false;
}
// 清掉 proxy input
this.proxy_input.remove();
this.proxy_input = null;
return true;
}
}
这样 overwrite blur 事件後,就可以直接对 div bind blur 了:
$('div.test').blur(function(){ console.log('blur div.test') });
要特别说明的是,做出来的 proxy_input 会放在原来的 element 的上方,目的是要
让使用者在 click 原来的 element 时,其实却 click 到了我们的 proxy_input
为了让使用者看不到我们的 proxy_input ,要加上特别的 style
input.proxy_input { position: absolute;
filter:alpha(opacity=0);
opacity: 0;
-moz-opacity:0;
}
以上的 code 只在 firefox 中测试过..
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.135.70.236
1F:→ TonyQ:soga , 原来是透明後完全盖住 , 这倒是没想到. GJ :p 09/19 09:48
2F:→ TonyQ:不晓得这样对原本元素的hover/click等事件还会不会存在:p 09/19 09:59
3F:→ TonyQ:这有测试的价值 , 找个时间来测一下... 09/19 09:59
4F:→ contagious:查了一下..其实好像只要加上 tabindex 就可以 focus 了 09/19 12:46
5F:→ contagious:不过初步测试 ff/ie 都可以..但是 safari 不行... 09/19 12:47
7F:→ TonyQ:soga .. 感恩这情报. 09/19 13:33
8F:→ TonyQ:找时间测试一下 , 很感谢你对这问题的不吝分享. :p 09/19 13:35