[英]Hide element onFocus and display onBlur
I have 2 form inputs where onFocus I want to hide another element on the page. 我有2个表单输入,我想在onFocus上隐藏页面上的另一个元素。
$(document).ready(function () {
$('.email').focus(function () {
$('.note').fadeTo('fast', 0);
}).blur(function () {
$('.note').fadeTo('fast', 1);
});
$('.password').focus(function () {
$('.note').fadeTo('fast', 0);
}).blur(function () {
$('.note').fadeTo('fast', 1);
});
});
Pretty basic stuff, but I also need to ensure that when switching between these two inputs (.email & .password) that the hidden element doesn't become visible again. 很基本的东西,但是我还需要确保在这两个输入(.email和.password)之间切换时,隐藏元素不会再次变得可见。
It seems that sometimes when I switch between them that the hidden element flickers back into view, or that the .focus event isn't being fired because the element isn't in focus for some reason. 似乎有时当我在它们之间切换时,隐藏的元素会闪烁回到视野中,或者因为某些原因元素未处于焦点状态而未触发.focus事件。
Is there anyway for me to say, the .note element is hidden, if were switching between .email & .password remain hidden until focus is lost from both of these elements? 无论如何,我是否要说.note元素是隐藏的,如果.email和.password之间的切换保持隐藏,直到这两个元素失去焦点为止?
You could make use of :focus
to verify if the other field is currently focused. 您可以使用:focus
来验证其他字段当前是否处于焦点状态。
$(document).ready(function () {
$('.email').focus(function () {
$('.note').fadeTo('fast', 0);
}).blur(function () {
if ($('.password:focus').length == 0)
$('.note').fadeTo('fast', 1);
});
$('.password').focus(function () {
$('.note').fadeTo('fast', 0);
}).blur(function () {
if ($('.email:focus').length == 0)
$('.note').fadeTo('fast', 1);
});
});
I tried a few things on jsFiddle and came up with the following solution. 我在jsFiddle上尝试了一些方法,并提出了以下解决方案。 It appears that the blur()
is being executed before the focus()
, which is why it fades in then fades out immediately. 似乎在focus()
之前执行了blur()
,这就是为什么它渐渐淡入然后立即淡出的原因。
I put a timeout that delays the blur event after a short time, so we can check to see if a new element has been focused, before executing the blur. 我设置了一个超时,该超时会在很短的时间后延迟模糊事件,因此我们可以在执行模糊之前检查是否已聚焦了新元素。
$( document ).ready( function( ) {
$( '.email, .password' ).focus( function( ) {
$( '.note' ).fadeTo( 'fast', 0 );
} ).blur( function( ) {
setTimeout( function( ) {
if( $( '.email:focus, .password:focus' ).length == 0 )
{
$( '.note' ).fadeTo( 'fast', 1 );
}
}, 100 );
} );
} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.