$.fn.extend({
blurIfNot : function(options, handler)
{
var defaults =
{
except : [],
maxParent : null // A DOM element within which
// a matching element may be found
};
var opt = $.extend({}, defaults, options);
var time = new Date().getTime();
this.each(function()
{
var thisInp = $(this);
thisInp[0].blurIfNot = {};
time += 1000000000000;
var except = opt.except;
if ($.isFunction(opt.except))
{ except = opt.except.call(thisInp[0]); }
function fire_blur_event(_tar, evt, mousedown)
{
var proceed = true;
for (var i in except)
{
if (_tar.is(thisInp) ||
_tar.closest(except[i], opt.maxParent).length)
{
proceed = false;
break;
}
}
if (proceed)
{
thisInp[0].blurIfNot.focus = false;
handler.call(thisInp[0], evt);
}
else if (mousedown)
{
$('html').one('mouseup', function(e)
{
thisInp[0].focus();
});
}
}
if (!thisInp[0].blurIfNot.isset)
{
$('html').mousedown(function(e)
{
if (thisInp[0].blurIfNot.focus)
{
var tar = $(e.target);
if (!tar.is('input'))
{ fire_blur_event(tar, e, true); }
}
});
$(window).blur(function(e)
{
if (thisInp[0].blurIfNot.focus)
{
thisInp[0].blurIfNot.focus = false;
handler.call(thisInp[0], e);
}
});
}
else
{ // to be able to update the input event if you have
// created new inputs dynamically
$('input').off('focus.blufIfNot' + time);
}
$('input').on('focus.blurIfNot' + time, function(e)
{
var tar = $(e.target);
if (tar[0] == thisInp[0])
{ thisInp[0].blurIfNot.focus = true; }
else if (thisInp[0].blurIfNot.focus)
{ fire_blur_event(tar, e); }
});
thisInp[0].blurIfNot.isset = true;
});
return this;
}
});
$('#input_blur_if_not').blurIfNot(
{
except : [
$('.autocomplete'), $('.question')
],
// You can also define the elements with a function:
// except : function()
// {
// return [ $(this).parent().find('.autocomplete') ];
// },
maxParent : $('#parent')[0] // optional
},
function(e)
{
var rand = Math.random();
$('#test').css('padding', rand * 100 + "px").
html(rand + " blur !");
});
.autocomplete {
background: #eee;
}
.autocomplete, input {
width: 200px;
padding: 3px;
border: 1px solid #555;
}
.question {
display:inline-block;
border-radius:50%;
background:#137dba;
color:#fff;
font-weight:bold;
padding:2px 7px;
cursor:pointer;
}
#test {
position:absolute;
top:0;
left:260px;
color:red;
font-weight:bold;
padding:10px 0;
vertical-align:bottom;
}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<div id="parent">
<input value="an input" />
<br><br>
<input id="input_blur_if_not" value="input with autocomplete menu" />
<div class="question">?</div>
<div class="autocomplete">
<div>option 1</div>
<div>option 2</div>
</div>
<br>
<input value="another input" />
<div id="test"></div>
</div>
hiển thị những gì bạn đã mã hóa cho đến thời điểm này. –
Bạn sẽ cần phải có 'e.preventDefault',' e.stopPropagation', hoặc xác định cái nào đã được nhấp và dừng bọt trước khi nó chạm vào mục tiêu. Lỗ hổng thiết kế mà tôi cảm thấy là bạn có trình xử lý sự kiện mờ trên DOM? Tôi có hiểu điều đó đúng không? –