簡體   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