在 svelte 上禁用输入字段中的空格

Disable spaces in input field on svelte

我正在尝试禁用用户名文本字段中的 spaces

作为Disable spaces in Input, AND allow back arrow?,应该是这样的:

<input on:keydown={(e) => e.which !== 32} />

但我仍然可以输入space

which 不再是有效事件 属性。对于键盘事件,您需要使用 KeyboardEvent.code or KeyboardEvent.key.

在您的用例中,使用前者:

<input on:keydown={({ code }) => code !== "Space"} />

然而,这只会禁止空格键,因此您可能必须添加对其他空格键的处理,例如 Tab

或者,您可以将您的输入转换为受控输入,并且 trim 内容在任何时候发生变化(实际上不允许任何类型的空格输入)。

对于标准事件处理,return 值没有意义。你应该使用 preventDefault.

示例代码:

Broken:
<input type="text" on:keypress="{e => e.charCode != 32}"/> <br/>

Works (not recommended):
<input type="text" onkeypress="return event.charCode != 32"/> <br/>

Works with "on:"
<input type="text"
       on:keypress={e => { if (e.charCode == 32) e.preventDefault(); }} />

(此外,keypress 事件已弃用,不应再使用。此外,这只是部分解决方案,因为用户仍然可以粘贴任何值。)

REPL

这是一个解决方案,可以防止输入空格并将其从粘贴的文本中删除REPL

<script>
    let value
    
    function handleKeydown(event) {
        // prevent that a space is typed
        if(event.code === 'Space') event.preventDefault()
    }
    
    function handleInput(event) {
        // remove spaces from pasted text
        value = value.replaceAll(' ', '')       
    }   
</script>

<input type="text"
             bind:value
             on:keydown={handleKeydown}
             on:input={handleInput}>