Lyo*_*yon 19 jquery focus blur
使用以下代码,当输入字段处于焦点/模糊时,我能够进行隐藏的div显示/隐藏:
$('#example').focus(function() {
$('div.example').css('display','block');
}).blur(function() {
$('div.example').fadeOut('medium');
});
Run Code Online (Sandbox Code Playgroud)
问题是,div.example
当用户在此div中进行交互时,我希望继续可见.例如,单击或突出显示其中的文本等div.example
.但是div.example
,只要输入不在焦点并且鼠标与div中的元素交互,就会淡出.
输入和div元素的html代码如下:
<p>
<label for="example">Text:</label>
<input id="example" name="example" type="text" maxlength="100" />
<div class="example">Some text...<br /><br />More text...</div>
</p>
Run Code Online (Sandbox Code Playgroud)
我如何使它div.example
只在用户点击输入外部和/或div.example
?时消失?我尝试使用focusin/focusout来检查焦点,<p>
但这也没有用.
div.example
使用jQuery直接位于输入字段#example下方是否重要?执行此操作的代码如下:
var fieldExample = $('#example');
$('div.example').css("position","absolute");
$('div.example').css("left", fieldExample.offset().left);
$('div.example').css("top", fieldExample.offset().top + fieldExample.outerHeight());
Run Code Online (Sandbox Code Playgroud)
如果以前曾经问过这个问题,我很抱歉,但是我读过的许多显示/隐藏div问题并没有涵盖这一点.谢谢你的建议.:)
Pet*_*dIt 29
如果你跟踪焦点气泡,那么你就可以找到焦点气泡,然后你可以弄清楚焦点中的新事物是否在"外部",如果是,那么就可以做些什么.这适用于点击和标签.
$('#example').focus(function() {
var div = $('div.example').show();
$(document).bind('focusin.example click.example',function(e) {
if ($(e.target).closest('.example, #example').length) return;
$(document).unbind('.example');
div.fadeOut('medium');
});
});
$('div.example').hide();?
Run Code Online (Sandbox Code Playgroud)
更新了代码以使用focusin和click事件来决定是否隐藏div.example.我正在使用命名空间事件,以便我可以调用unbind('.example')取消绑定它们.
示例:http://jsfiddle.net/9XmVT/11/
Side Note 将您的css定位代码更改为仅调用一次css方法:
$('div.example').css({
"position":"absolute",
"left": fieldExample.offset().left,
"top": fieldExample.offset().top + fieldExample.outerHeight()
});
Run Code Online (Sandbox Code Playgroud)
使用绝对定位div的示例:http://jsfiddle.net/9XmVT/14/
UPDATE
Ben Alman刚刚更新了他的clickoutside事件并将其转换为处理很多*外部事件. http://benalman.com/projects/jquery-outside-events-plugin/
会让你做这样的事情:
$('#example').focus(function() {
$('div.example').show().bind('focusoutside clickoutside',function(e) {
$(this).unbind('focusoutside clickoutside').fadeOut('medium');
});
});
$('div.example').hide();
Run Code Online (Sandbox Code Playgroud)