0

我只是在玩媒体编辑器,我发现了一些特别的东西。写作时,如果您尝试多次点击空格,则它不起作用意味着编辑器不接受多个空格。多么酷。

在此处输入图像描述

如果我们在textareascontenteditable中实现它以限制用户输入大量空格,那将会很酷。

如果有人知道怎么做,请与我分享。

更新

<h2 contenteditable="true">Write here</h2>

我如何限制用户点击多个空格。

4

1 回答 1

0

我用textarea试过了。在此文本区域中输入字符时,您将不能输入多个空格。这是你要找的吗?:

function trimSpaces(event){
   var content = $('#sampleText').val();
   //If you need to trim all white spaces and replace with single space
   //content = content.replace(/\s\s+/g, ' ');

   $('#sampleText').val("");
   content = content.replace(/  +/g, ' ');
   $('#sampleText').val(content);
}

function validate(event){
    // Donot add the character keyed into textbox before validation
	event.preventDefault();
	var content = $('#sampleText').val();
    //which is supported by FF and keyCode by other browsers. 
	var x = event.which || event.keyCode;
	
	if(x==32){
	  if( content[content.length -1] ==" "){
         // Do nothing if previous character was a space
	  }else{
        // Add the character into the text area if its not a space
		content+=String.fromCharCode(x);
		$('#sampleText').val(content);
	  }
	}else{
        // add any characters keyed in to the text area if its not a space.
		content+=String.fromCharCode(x);
		$('#sampleText').val(content);
	}	
}
<!DOCTYPE html>
<html>

</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<body>
  <textarea name="sampleText" id="sampleText" maxlength="200" onkeypress="validate(event)" onkeyup="trimSpaces(event)"></textarea>
</body>
</html>

于 2020-05-15T06:29:45.877 回答