为什么我不能集中使用slideDown()显示的控件?

时间:2021-06-25 21:10:58

I want to reveal a div with an input inside when you click a button, and set its focus.

我想在单击按钮时显示带有输入的div,并设置其焦点。

If I use show(), it works, but if I use slideDown() the focus is lost after the animation completes. How can I prevent this from happening?

如果我使用show(),它可以工作,但是如果我使用slideDown(),则在动画完成后焦点会丢失。我怎样才能防止这种情况发生?

Sample code:

$("document").ready(function(){
    $("#MyButton").click(function(e){
        e.preventDefault();
        $(".SlidingDiv").slideDown();
        $("#MyInput").focus();
    });
});

<input type="button" value="Click Me" id="MyButton" />
<div class="SlidingDiv" style="display:none;"><input type="text" id="MyInput" /></div>

2 个解决方案

#1


10  

Try this:

$(function(){
    $("#MyButton").click(function(e){
        e.preventDefault();
        $(".SlidingDiv").slideDown(function(){
            // Callback function - will occur when sliding is complete.
            $("#MyInput").focus();
        });
    });
});

#2


1  

I think you can only focus the element once the DIV has fully stopped sliding?
not sure...

我认为你只能在DIV完全停止滑动后关注元素?不确定...

#1


10  

Try this:

$(function(){
    $("#MyButton").click(function(e){
        e.preventDefault();
        $(".SlidingDiv").slideDown(function(){
            // Callback function - will occur when sliding is complete.
            $("#MyInput").focus();
        });
    });
});

#2


1  

I think you can only focus the element once the DIV has fully stopped sliding?
not sure...

我认为你只能在DIV完全停止滑动后关注元素?不确定...