How to focus on newly added inputs in Svelte?

 ̄綄美尐妖づ 提交于 2019-12-10 16:14:00

问题


I use #each to display an input for every member of the tasks array. When I click the Add task button, a new element is inserted into the array, so a new input appears in the #each loop.

How do I focus the input that's been added upon clicking the Add task button?

<script>
  let tasks = [];

  function addTask() {
    tasks = [...tasks, { title: "" }];
  }
</script>

{#each tasks as task}
  <input type="text" bind:value={task.title} />
{/each}

<button on:click={addTask}>Add task</button>

回答1:


Rich Harris has a nicer solution


You can use use:action:

Actions are functions that are called when an element is created.

For example:

<script>
  let tasks = [];

  function addTask() {
    tasks = [...tasks, { title: "" }];
  }

  function init(el){
    el.focus()
  }
</script>

{#each tasks as task}
  <input type="text" bind:value={task.title} use:init />
{/each}

<button on:click={addTask}>Add task</button>



回答2:


You can use the autofocus attribute:

<script>
  let tasks = [];

  function addTask() {
    tasks = [...tasks, { title: "" }];
  }
</script>

{#each tasks as task}
  <input type="text" bind:value={task.title} autofocus />
{/each}

<button on:click={addTask}>Add task</button>

Note that you'll get an accessibility warning. That's because accessibility guidelines actually recommend that you don't do this:

People who are blind or who have low vision may be disoriented when focus is moved without their permission. Additionally, autofocus can be problematic for people with motor control disabilities, as it may create extra work for them to navigate out from the autofocused area and to other locationso on the page/view.

It's up to you to determine whether this advice is relevant in your situation!



来源:https://stackoverflow.com/questions/57257499/how-to-focus-on-newly-added-inputs-in-svelte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!