Svelte:select 焦点输入元素的文本

Svelte: select text of input element on focus

我想select input 元素的文本获得焦点。我尝试使用 bind:this={ref},然后使用 ref.select(),但这似乎只有在我从 input 元素中删除 bind:value 时才有效。为什么?以及如何解决?

非常感谢!

<script lang="ts">
    import { evaluate } from 'mathjs';

    export let value: string | number = 0;
    let ref;

    function handleFocus() {
        value = value?.toString().replace('.', '').replace(',', '.');
        ref.select();
    }

    function handleBlur() {
        value = parseFloat(evaluate(value?.toString())).toLocaleString('be-NL', {
            maximumFractionDigits: 2,
            minimumFractionDigits: 2
        });
    }
</script>

<input
    class="text-right"
    autocomplete="off"
    type="text"
    bind:value
    bind:this={ref}
    on:focus={handleFocus}
    on:blur={handleBlur}
/>

正如@JHeth 的评论所述: 我添加了 await tick(),创建了函数 async,它起作用了。

<script lang="ts">
    import { evaluate } from 'mathjs';

    export let value: string | number = 0;
    let ref;

    async function handleFocus() {
        value = value?.toString().replace('.', '').replace(',', '.');
        await tick();
        ref.select();
    }

    function handleBlur() {
        value = parseFloat(evaluate(value?.toString())).toLocaleString('be-NL', {
            maximumFractionDigits: 2,
            minimumFractionDigits: 2
        });
    }
</script>

<input
    class="text-right"
    autocomplete="off"
    type="text"
    bind:value
    bind:this={ref}
    on:focus={async () => handleFocus()}
    on:blur={handleBlur}
/>

您可以在输入标签中内联:

<input on:focus="{event => event.target.select()}">

或者将事件传递给一个函数并做更多的事情:

<script>
    function selectContentAndDoStuff (event) {
        console.log("event: ", event);
        event.target.select();
        console.log("do more stuff here")
    }
</script>

<input on:focus="{event => selectContentAndDoStuff(event)}">