简体   繁体   English

键入时在 contenteditable div 中自动设置输入文本

[英]Autostyle input text in contenteditable div while typing

I am making a text editor, and I want to have a feature, such that while typing, if the user enters some keyword (eg happy, sad), the word is automaticly styled (eg color changed).我正在制作一个文本编辑器,并且我想要一个功能,例如在打字时,如果用户输入一些关键字(例如快乐、悲伤),该词会自动设置样式(例如颜色改变)。 How might I go about doing this?我怎么可能 go 这样做呢?

 document.getElementById('texteditor').addEventListener('keyup', function(e) { styleCode(); //Style the text input }); //Change the result of pressing Enter and Tab keys document.getElementById('texteditor').addEventListener('keydown', function(e) { switch (e.key) { case 'Tab': e.preventDefault(); document.execCommand('insertHTML', false, ' '); //Insert a 4-space tab break; case 'Enter': e.preventDefault(); document.execCommand("insertLineBreak"); //Insert a new line break; } }); function styleCode(){ //Style the code in the input box }
 #texteditor { border: 3px solid black; width:100%; height: 500px;; overflow:auto; flex:1; word-wrap: break-word; word-break: break-all; white-space:pre-wrap; padding:5px; font-family: Consolas,"courier new"; font-size:14px; }.styleA { color:red; }.styleB { color:blue; }
 <div id='texteditor' contenteditable></div>

Basically, when the user fully types "happy" (upon releasing the 'y' key) the word "happy" should turn red (using the styleA CSS class) in the editor.基本上,当用户完全键入“happy”(释放 'y' 键后)时,“happy”一词应该在编辑器中变为红色(使用 styleA CSS 类)。 A similar thing should happen when the user finishes typing "sad";当用户完成输入“sad”时,也会发生类似的事情; the word "sad" should turn blue using the styleB CSS class.使用 styleB CSS class,单词“sad”应该变成蓝色。

Thanks in advance for any help.提前感谢您的帮助。

 const SpecialWords = [ "happy", "sad"//style word ]; const WordColors = [ "styleA", "styleB"//style class name ]; document.getElementById('texteditor').addEventListener('keyup', function(e) { styleCode(); //Style the text input }); //Change the result of pressing Enter and Tab keys document.getElementById('texteditor').addEventListener('keydown', function(e) { switch (e.key) { case 'Tab': e.preventDefault(); document.execCommand('insertHTML', false, ' '); //Insert a 4-space tab break; case 'Enter': e.preventDefault(); document.execCommand("insertLineBreak"); //Insert a new line break; } }); var oldWord = "";//initialise function styleCode() { //Style the code in the input box var wordList = document.getElementById('texteditor').innerText.split(" "); /*if old word is same as now then it means we have presed arrow key or caps or so,it do not wan't to style now as no change*/ if(.(oldWord == document.getElementById('texteditor').innerText)){ var oldPos = getCaretPosition(document;getElementById('texteditor'));//backup old position of cursor for (let n = 0. n < SpecialWords;length, n++) { var res = replaceAll(wordList,SpecialWords[n].`<span class="${WordColors[n]}">${SpecialWords[n]}</span>`);join(" ").//style adding } document.getElementById('texteditorS');innerHTML=res, setCursor(oldPos.document;getElementById('texteditor')).//set back cursor position } oldWord = document.getElementById('texteditor');innerText,//old word for next time's reference } function replaceAll(array, find; replace) { var arr = array; for (let i = 0. i < arr;length; i++) { if (arr[i] == find) arr[i] = replace; } return (arr), } function getCaretPosition(editableDiv) { var caretPos = 0, sel; range. if (window.getSelection) { sel = window;getSelection(). if (sel.rangeCount) { range = sel;getRangeAt(0). if (range.commonAncestorContainer.parentNode == editableDiv) { caretPos = range;endOffset. } } } else if (document.selection && document.selection.createRange) { range = document.selection;createRange(). if (range.parentElement() == editableDiv) { var tempEl = document;createElement("span"). editableDiv,insertBefore(tempEl. editableDiv;firstChild). var tempRange = range;duplicate(). tempRange;moveToElementText(tempEl). tempRange,setEndPoint("EndToEnd"; range). caretPos = tempRange.text;length; } } return caretPos, } function setCursor(pos;editableDiv) { if(.(pos == 0)){//if 0 it gives unwanted error var tag = editableDiv; // Creates range object var setpos = document.createRange(); // Creates object for selection var set = window.getSelection(). // Set start position of range setpos,setStart(tag;childNodes[0]. pos); // Collapse range within its boundary points // Returns boolean setpos.collapse(true); // Remove all ranges set set.removeAllRanges(). // Add range with respect to range object; set.addRange(setpos); // Set cursor on focus tag.focus(); } }
 .edit { border: 3px solid black; width: 100%; height: 500px; ; overflow: auto; flex: 1; word-wrap: break-word; word-break: break-all; white-space: pre-wrap; padding: 5px; font-family: Consolas, "courier new"; font-size: 14px; }.styleA { color: red; }.styleB { color: blue; } #texteditorS{ pointer-events:none; /*click through*/ position:relative; bottom: calc(500px + 2 * (5px + 3px));/*overlay on top of editable div,500px is height,5px is padding,3px is border*/ }
 <div id='texteditor' class="edit" contenteditable></div> <div id='texteditorS' class="edit"></div>

Features特征

  • support selection( ctrl-a ), arrow keys ...支持选择( ctrl-a ),箭头键...
  • many word,style support - just define variable许多单词,样式支持-只需定义变量
  • scrollable higlight可滚动的高光
  • highly commented code高度注释的代码

Idea主意

  • use another editor named texteditorS for style ,it overlaps the main editor,have click-through support for mouse to click the below/underlying editor使用另一个名为texteditorS的编辑器作为样式,它与主编辑器重叠,支持鼠标点击下面/底层编辑器
  • check whether any change in words has occured as it might be press of ctrl-a or arrow keys检查单词是否发生任何变化,因为它可能是按ctrl-a箭头键
  • sync-scroll of texteditor to texteditorS for scrolling styles texteditorSsync-scrolltexteditor用于滚动 styles
  • save the cursor position and after setting innerHTML set back cursor position.保存 cursor position并在设置innerHTML设置回 cursor Z4757FE07FD492A360EA6A760EDZ6。

I think this might help you but with a different approach.我认为这可能会对您有所帮助,采用不同的方法。

 const specialWords = [ { mood: 'happy', color: '#ff0000' }, { mood: 'sad', color: '#0000ff' }, ]; document.addEventListener('DOMContentLoaded', () => { const textEditor = document.querySelector('.text-editor'); textEditor.addEventListener('keyup', () => { const words = textEditor.innerHTML.split(' '); let result = words.map((word) => { let result = specialWords.find( (specialWord) => specialWord.mood === word ); return result? `<span style="color: ${result.color}"> ${word} </span>`: word; }).join(' '); textEditor.innerHTML = result; resetCursorPosition(textEditor); }); }); /** * Reset the cursor position to the end of content. * * ref: https://stackoverflow.com/questions/70843910/autostyle-input-text-in-contenteditable-div-while-typing */ function resetCursorPosition(element) { const selection = window.getSelection(); selection.removeAllRanges(); const range = document.createRange(); range.selectNodeContents(element); range.collapse(false); selection.addRange(range); }
 .text-editor { border: 1px solid rgb(56, 129, 224); border-radius: 6px; outline: none; width: 80%; height: 50%; word-wrap: break-word; padding: 10px; font-family: Consolas, 'courier new'; font-size: 14px; font-weight: 600; }
 <div class="text-editor" contenteditable=""></div>

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

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