最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to auto-focus after changing display from none to block? - Stack Overflow

programmeradmin1浏览0评论

I have a list of inputs under a list of divs respectively. I have a button that when clicked it will switch one input from from not display to display. This is something like:

if (switched) {
        document.getElementById("div-xxx").style.display = "block";
}

However, is there a way I could make the input inside the displayed div being auto focused after this switch? I tried something like

document.getElementById('input-xxx').autofocus = true;

after the display code, but there is no autofocus at all.

I have a list of inputs under a list of divs respectively. I have a button that when clicked it will switch one input from from not display to display. This is something like:

if (switched) {
        document.getElementById("div-xxx").style.display = "block";
}

However, is there a way I could make the input inside the displayed div being auto focused after this switch? I tried something like

document.getElementById('input-xxx').autofocus = true;

after the display code, but there is no autofocus at all.

Share Improve this question edited Oct 23, 2019 at 4:01 John M. asked Oct 23, 2019 at 1:00 John M.John M. 9052 gold badges10 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

document.getElementById('input-xxx').focus() will change the focus to the selected element.

document.getElementById('input-xxx').setAttribute('autofocus', true) will assign the autofocus attribute to the html element

object.focus(); will help

if (switched) {
        document.getElementById('div-xxx').style.display = "block";
        document.getElementById('input-xxx').focus();
}

The only thing that worked for me was

    if (switched) {

        document.getElementById('div-xxx').style.display = "block";
        document.getElementById('old-input').setAttribute('autofocus', false);
        document.getElementById('input-xxx').setAttribute('autofocus', true);
        document.getElementById('input-xxx').focus();
}

发布评论

评论列表(0)

  1. 暂无评论