搜索按钮显示搜索表单后,将焦点移至搜索框

时间:2019-07-13 19:21:10

标签: html focus

我有一个单击图标时出现的搜索表单。但是焦点仍然停留在图标上,用户必须再次在搜索框中单击才能键入。表单出现后如何将焦点移至输入框?

我的代码如下。

图标:

<span class="search-item">
<button aria-expanded="false" class="search-toggle">
<svg class="icon icon-search" aria-hidden="true" role="img" focusable="false">
<use href="#icon-search" xlink:href="#icon-search"></use>
</svg>
<svg class="icon icon-close" aria-hidden="true" role="img" focusable="false">
<use href="#icon-close" xlink:href="#icon-close"></use>
</svg>
</button>
</span>
点击图标时打开的

FORM

<form role="search" method="get" class="search-form" itemprop="potentialAction" itemscope="itemscope" itemtype="http://schema.org/SearchAction" action="https://www.example.com/">
<label class="label-search">
<span class="screen-reader-text">SEARCH</span>
<input type="search" class="search-field" itemprop="query-input" placeholder="Search..." value="" name="s" title="Search">
</label>
<button type="submit" class="search-submit">
<svg class="icon icon-search" aria-hidden="true" role="img" focusable="false">
<use href="#icon-search" xlink:href="#icon-search"></use>
</svg>
<span class="screen-reader-text">SEARCH</span>
</button>
</form>

搜索功能,来自functions.php:

public static function primary_nav_search( $args ) {
    if ( 'primary' !== $args['theme_location'] ) {
        return $args;
    }

    if ( '' === get_theme_mod('manta_nav_search', manta_get_theme_defaults( 'manta_nav_search' ) ) ) {
        return $args;
    }

    $search_toggle = sprintf( '<button aria-expanded="false"%1$s>%2$s%3$s</button>', manta_get_attr( 'search-toggle' ), manta_get_icon( array( 'icon' => 'search' ) ), manta_get_icon( array( 'icon' => 'close' ) ) );
    $search_item   = sprintf( '<span%1$s>%2$s</span>', manta_get_attr( 'search-item' ), $search_toggle );

    $args['items_wrap'] = get_search_form( false ) . $args['items_wrap'] . $search_item;
    return $args;
}

这可以做到吗?谢谢。

1 个答案:

答案 0 :(得分:1)

编辑:糟糕,我在这里看不到js,但是您仍然可以使用HTML <script>标签

您应该考虑使用 javascript element.blur()删除焦点,并使用element.focus()将焦点设置在另一个元素上。

更多信息:

Blur()- https://www.w3schools.com/jsref/met_html_blur.asp

Focus()- https://www.w3schools.com/jsref/met_html_focus.asp

在您的HTML文件中,尝试以下操作:

<script>
    const iconSearch = document.querySelector('.search-toggle');
    const searchField = document.querySelector('.search-field');

    iconSearch.addEventListener("click", function () {
        searchField.focus();
    });
</script>