【问题标题】:Medium editor does not take more than one space is anyone know how to do that?中型编辑器占用的空间不超过一个空间有人知道该怎么做吗?
【发布时间】:2020-05-15 05:31:32
【问题描述】:

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

如果我们在 textareascontenteditable 中实现此功能以限制用户输入大量空格,那就太棒了。

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

更新

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

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

【问题讨论】:

  • @Teemu 如何使用 javascript 进行操作。
  • @Teemu 有一个用例。我更新了我的问题。
  • 嗯......我不知何故错过了实际问题。 contenteditable API 在所有浏览器中都很糟糕,当您输入多个空格时,它会创建 &amp;nbsp; 实体,无论如何都允许使用纯文本。您必须捕获输入(击键、粘贴、删除)并删除额外的间距。这项任务并非微不足道,需要对 textareas 和 contenteditables 采用不同的方法,希望尝试解决该问题。
  • @Teemu 我试图解决这些事件,它正在工作但不完全正确。我可以给你看一个 codepen 的例子吗?
  • 是的,当然。

标签: javascript html frontend web-deployment medium-editor


【解决方案1】:

我用 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>

【讨论】:

  • 您仍然可以将带有多个空格的值粘贴和拖放到文本区域。 event.whichevent.keyCode 都已弃用。
  • @Teemu - 使用正则表达式可以处理带有多个空格的粘贴。 event.which 和 event.keycode 是迄今为止我们可以用来获得所需输出的最好的。如果有其他方法,请告诉我。修改了代码以处理按键时的粘贴场景。
  • @thommu 有一个问题。光标无法返回。如果我想在前一个单词之间添加空格怎么办
  • @thommu 请看一下我在问题的评论线程中链接的小提琴。此外,还有新的事件属性:event.keyevent.code,这些属性将在近期(?)将来替换旧属性,并且不推荐使用的属性将一起被删除。见前。 KeyboardEvent.which.
猜你喜欢
  • 2018-01-11
  • 2010-11-09
  • 2016-05-30
  • 2011-01-16
  • 2013-08-03
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多