简体   繁体   English

如何在 HTML 输入的字符前后添加空格

[英]How I can add spaces before and after character on HTML input

I want to add spaces in my input field after every time when I click any symbol in my keyboard,How I can do that?每次单击键盘上的任何符号后,我都想在输入字段中添加空格,我该怎么做?

This is an early solution that still uses the change event listening for any change occurring on the input box and that will deal with text content replacing only characters not being any letter a-zA-Z nor number 0-9 nor space.这是一个早期的解决方案,它仍然使用change事件侦听输入框上发生的任何更改,并且将处理文本内容,仅替换不是任何字母a-zA-Z 、数字0-9或空格的字符。

The change event to occur requires you to switch focus to a different element.要发生的change事件需要您将焦点切换到不同的元素。 Otherwise keydown or input (as suggested in comments) was more appropriate.否则keydowninput (如评论中所建议的)更合适。 Anyway since the content might change in several ways, including pasting, its input must be processed in its entirety each time the event occur and you can't rely on the last character pressed only.无论如何,由于内容可能会以多种方式发生变化,包括粘贴,因此每次事件发生时都必须完整地处理其输入,并且您不能仅依赖于最后按下的字符。

I used the regex replace strategy but it's still weak because your feedback was lacking.我使用了正则表达式替换策略,但它仍然很弱,因为缺少您的反馈。

 init(); function init(){ document.querySelectorAll('.controlled').forEach((o,i)=>{ o.addEventListener('change', (event)=>{ const subject = event.target.value; const result = subject.replace(/[^a-zA-Z0-9\s]/img, " $& "); console.log(result); event.target.value = result; }); }); }
 .controlled{ font-size: 20px; padding:.5rem; }.field{ padding: 1rem; border: dashed 3px gray; }
 <div class="field"> <p>Change the value of the input box, and when you switch focus to a different element,<br> the content will be transformed so that any symbol will have added space before and after:</p> <input type="text" class="controlled"> </div>

You can use &ensp to insert space in HTML您可以使用 &ensp 在 HTML 中插入空格

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

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