繁体   English   中英

单词之间不应允许超过一个空格

[英]should not allow more than one space in between words

function stripspaces(input)
{
    input.value = input.value.replace(/\s+/gi," ");

}

我写了这个函数。 它正在工作,但是当我将鼠标指针指向或在单词之间用左箭头移动并留出空间时,它会跳到最后。 谁能给我解决方案?

您可以通过调用e.preventingDefault来阻止输入,我们可以简单地测试是否按下了空格键以及光标两侧是否有空格然后阻止输入。

 document.addEventListener('DOMContentLoaded', function() { var input = document.getElementById('myInput'); input.addEventListener('keydown', function(e){ var input = e.target; var val = input.value; var end = input.selectionEnd; if(e.keyCode == 32 && (val[end - 1] == " " || val[end] == " ")) { e.preventDefault(); return false; } }); });
 <input type="text" id="myInput">

这仍然存在一个问题,即它不会阻止粘贴到带有双空格的框中。 因此,仍然值得在焦点丢失时替换多个空格,以确保输入永远不会包含多个连续空格。

我刚刚遇到了相同的用例。 如果您还想处理复制/粘贴或输入值可能更改的任何其他方式,请使用输入事件

 document.addEventListener('DOMContentLoaded', function() { // get a reference to the input element const input = document.querySelector('#myInput'); // guard clause to check if `#myInput' actually exists in the current DOM if(!input) return // Run this every time the input's value changes input.addEventListener('input', e => { // get the value const value = e.target.value // check if the value isn't exactly ' ' and ends with a space const hasTrailingSpace = value !== ' ' && value.charAt(value.length-1) === ' ' // extract words, remove empty words (handles double spaces) const words = value.split(' ').filter(el => el !== '') // create the sanitized value let sanitizedValue = words.join(' ') // add a trailing space if there was one if( hasTrailingSpace ) sanitizedValue += ' ' // apply the sanitized value to the input's value e.target.value = sanitizedValue }) })
 <p>Try inserting double spaces now! Also try copy/paste from somewhere else</p> <input type="text" id="myInput">

暂无
暂无

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

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