[英]jQuery event only if two elements are not focused
我有一個名字和一個姓氏文本字段。 我想在它們中的任何一個都聚焦時顯示一行文本,並且僅在兩個元素都沒有聚焦時才隱藏該文本行。
每當我將焦點從姓氏更改為姓氏時,我當前的代碼都會翻轉文本(隱藏然后取消隱藏)。
我知道為什么,名字變得模糊(觸發隱藏動畫),然后姓氏成為焦點(觸發顯示動畫)。 由於明顯的原因,這是不可取的,我正在尋找一種解決方案。
HTML
<input type="text" placeholder="First" id="first" name="first" required>
<input type="text" placeholder="Last" id="last" name="last" required>
<p id="nameTxt" style="display: none">Blah blah blah</p>
腳本
$('#first, #last').focus(function() { $("#nameTxt").show(300); });
$('#first, #last').blur(function() { $("#nameTxt").hide(150); });
你可以這樣做:
var timerID;
$('#first, #last').focus(function() {
clearTimeout(timerID);
$("#nameTxt").show(300);
}).blur(function() {
timerID = setTimeout(function() {
$("#nameTxt").hide(150);
}, 10);
});
演示: http : //jsfiddle.net/VBwYE/
也就是說,使用setTimeout()
將#nameTxt
隱藏延遲僅幾毫秒,然后在焦點處理程序中取消超時。 請注意,您可以將.focus().blur()
在一起,以避免再次選擇相同的兩個元素。
這是一個有趣的! 這是一個想法。 您可以執行以下操作:
$(document).mousedown(function(){
if ($(event.target).attr("id") != "first" && $(event.target).attr("id") != "last") {
// hide it
}
else{
//show it
}
});
不過僅適用於點擊。
$("#first, #last").blur(function() {
if ($("#first:focus, #last:focus").length == 0) {
$("#nameTxt").hide(150);
}
});
嘗試
var $nt = $("#nameTxt");
$('#first, #last').focus(function () {
clearTimeout($nt.data('nttimer'))
$("#nameTxt").show(300);
});
$('#first, #last').blur(function () {
var timer = setTimeout(function () {
$("#nameTxt").hide(150);
}, 200);
$nt.data('nttimer', timer);
});
演示: 小提琴
嘗試這個::
<script>
$('#first, #last').focus(function() { $("#nameTxt").show(300); });
$('#first, #last').on("blur focusout", function() { $("#nameTxt").hide(150); });
</script>
因為某些瀏覽器不支持模糊事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.