无法在搜索表单中启用自动对焦

Can't enable autofocus in search form

我为搜索字段创建了一个 div,并使用 JS 代码通过单击导航栏中的图标使其从顶部显示。我想在输入中启用自动对焦,但它不起作用。我正在使用 Bootstrap 4。这是我使用的代码:

HTML:

<div id="top-header">
    <div class="container">
        <?php get_search_form(); ?>
        <button type="button" id="search-close-button" class="close" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
</div>

searchform.php:

<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label>
    <input type="search" class="search-field form-control" autofocus>
</label>
<input type="submit" class="search-submit btn" value="<?php echo esc_attr_x( 'procurar', 'submit button', 'wp-bootstrap-starter' ); ?>">

JS:

jQuery(document).ready(function ($) {
    $('#search-icon').click(function () {
        $('#top-header').addClass('show');
    });
    $('#search-close-button').click(function () {
        $('#top-header').removeClass('show');
    });
});

CSS:

#top-header {
    height: 5rem;
    background: #ffffff;
    position: fixed;
    width: 100%;
    z-index: 99999;
    top: 0;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    transform: translatey (-100%);
    -webkit-transform: translatey (-100%);
    -moz-transform: translatey (-100%);
    -ms-transform: translatey (-100%);
    -o-transform: translatey (-100%);
    transition: all .4s ease-in-out;
    -webkit-transition: all .4s ease-in-out;
    -moz-transition: all .4s ease-in-out;
    -ms-transition: all .4s ease-in-out;
    -o-transition: all .4s ease-in-out;
    opacity: 0;
}

#top-header.show {
    transform: translatey (0);
    -webkit-transform: translatey (0);
    -moz-transform: translatey (0);
    -ms-transform: translatey (0);
    -o-transform: translatey (0);
    -webkit-box-shadow: 0px 0px 5px 0px rgba (0, 0, 0, 0.2);
    -moz-box-shadow: 0px 0px 5px 0px rgba (0, 0, 0, 0.2);
    box-shadow: 0px 0px 5px 0px rgba (0, 0, 0, 0.2);
    opacity: 1;
}

有人可以帮助我吗?提前致谢!

你可以这样做:

$('#search-icon').click(function () {
    $('#top-header').addClass('show');
    $('.search-field').focus();
});