【问题标题】:Svelte: select text of input element on focusSvelte:在焦点上选择输入元素的文本
【发布时间】:2021-07-15 19:14:51
【问题描述】:

我想在焦点上选择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}
/>

【问题讨论】:

  • 我认为这是因为您在尝试选择文本之前更改了绑定到的值。如果您删除它应该选择的 value = value?.toString().replace('.', '').replace(',', '.'); 部分。或者,您可以使用setTimeout(()=&gt; ref.select(), 0) 或使用await tick() 并使您的函数异步,即使在select() 之前进行更改,它也应该可以正常工作。
  • await tick() 完美运行!谢谢

标签: typescript svelte


【解决方案1】:

正如@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}
/>

【讨论】:

    【解决方案2】:

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

    <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)}">
    

    【讨论】:

    • 只要使用on:focus={(evt) =&gt; evt.target.select()}
    猜你喜欢
    • 1970-01-01
    • 2013-02-06
    • 2019-04-27
    • 2013-05-13
    • 2017-09-26
    • 2020-07-25
    • 2011-09-22
    • 1970-01-01
    相关资源
    最近更新 更多