繁体   English   中英

Alpine.js - 显示输入字段并同时为其添加焦点

[英]Alpine.js - Show an input field and add focus to it at the same time

我有一个按钮,当用户单击它时,应该显示一个输入元素并且它应该具有焦点。

我试过这个:

<div x-data="{ show: false }">

    <input x-show="show" type="text" id="input" x-ref="input" />

    <button @click="show = !show; $refs.input.focus();">Button</button>

</div>

但它不起作用。

要在显示后立即关注输入,您需要使用 Alpine 的 $nextTick function。 试试这个稍微改动过的代码版本:

<div x-data="{ show: false }">

    <input x-show="show" type="text" id="input" x-ref="input" />

    <button @click="show = !show; $nextTick(() => { $refs.input.focus(); });">Button</button>

</div>

以下是有关 $nextTick 的更多信息: https://github.com/alpinejs/alpine#nexttick

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM