在设置display:block之后将焦点设置在输入元素上 [英] Setting focus on an input element after setting display:block

查看:185
本文介绍了在设置display:block之后将焦点设置在输入元素上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几行HTML:

I have an HTML along the following lines:

<div class="hiddenClass"> // this implies display:none
 <span>
    <input type="text" id="hiddenInput"/>
 </span>
</div>

和一个Javascript事件(在jQuery $ .ajax()调用的"succes"方法中触发),该事件需要使该div可见,然后将焦点设置到控件.像这样:

and a Javascript event (triggered in a "succes" method of an jQuery $.ajax() call ), that needs to make this div visible and then set the focus to the control. Something like:

 this.DOMElements.divElement.className="showClass"; //a CSS class with display:block;
 this.DOMElements.hiddenInputElement.focus();
 this.DOMElements.hiddenInputElement.select();

足够奇怪,此代码仅在部分时间有效.在某些情况下(仅有时!),focus/select命令会生成有关聚焦/选择不可见控件的警告.控件将变为可见,但焦点不会移动,文本也不会被选择.

strange enough, this code only works part of the time. In some cases (only sometimes!!) the focus/select commands generate warnings about focusing/selecting an invisible control. The control will be made visible, but the focus is not moved, nor is the text selected.

我找到了(某种程度上)解决方案,方法是将焦点/选择代码移到一个单独的函数中,然后通过

I found (somewhat) of a solution by moving the focus/select code in a separate function and delay-call it by means of a

this.DOMElements.divElement.className="showClass"; //a CSS class with display:block;
setTimeout("focusinput('hidddenInput')",1);

好吧,最后我的问题是:由于javascript是单线程的..在使父div可见的时间和可以对子input元素设置焦点/选择的时间之间,为什么会有延迟?这怎么可能是比赛条件?

Ok, finally my question: since javascript is single-threaded.. how come there is a delay between the time I made the parent div visible, and the time I can set the focus/select on the child input element ? How could this be a race condition?

在IE8中发生

推荐答案

如果您使用的是jQuery,请使用它来显示和设置焦点:

If you're using jQuery, use this to display and set focus:

$(".hiddenClass").fadeIn("fast", 
    function() {
        $("#hiddenInput").focus();
    }
);

$(".hiddenClass").show(0, 
    function() {
        $("#hiddenInput").focus();
    }
);

如果您想显示它而没有任何淡入.

If you want to show it without any fade in.

基本上,它会将隐藏的div淡入(如果您希望显示一个特定的div而不是所有带有.hiddenClass的元素,则可以用id替换.hiddenClass),一旦完成,它将执行回调函数以给出专注于输入.

Basically it's fading the hidden div in (you can replace .hiddenClass with an id if you one want a particular div to be shown and not all elements with .hiddenClass), and once it's done that it executes the callback function to give focus to the input.

这样,您就不会在完全显示div之后尝试赋予输入焦点.

That way you it will not try to give the input focus until after the div has been fully shown.

这篇关于在设置display:block之后将焦点设置在输入元素上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆