我已经为你构建了一个解决方案,
首先,您不能在输入标记的值内添加 HTML 标记。所以你必须使用contenteditable HTML 属性,通过在任何元素上将它设置为true contenteditable="true",你就可以开始编辑它的内容(写在里面)。
注意:我添加了背景颜色以使其在空白时可见
<div contentEditable="true" id="text" style="background-color: #eee;"></div>
您的 JavaScript (JQuery) 将如下所示:
请注意,您的代码有许多我必须修复的错误。
$('#text').keyup(function(){
// get the div element
let e = document.querySelector('#text');
// get only the text inside the element (without the HTML tags)
let str = e.innerText;
e.innerHTML = '';
// create a new element to contain our text because you cant add HTML text inside a DOM element directly
let tag = document.createElement('div');
let arr = str.split(" ");
// this string will contain our HTML and text
let newStr = ``;
$(arr).each((i,e)=>{
if(e[0]=="#")
{
newStr += `<strong>${e}</strong>`;
}
else{
newStr += `${e}`
}
newStr += ` `;
})
// add the string to the inner HTML of the element we created
tag.innerHTML = newStr;
// append the newly created element inside the div
e.append(tag);
// based on Vito Gentile answer
// this is to move the cursor to the end of the text we added, other wise the cursor would be at start of the text
cursorManager.setEndOfContenteditable(e);
});
我使用了this answer的代码,这就是cursorManager.setEndOfContenteditable(e);这行的来源。为方便起见,这是他们的代码。
(function( cursorManager ) {
//From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];
//From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
//Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
function canContainText(node) {
if(node.nodeType == 1) { //is an element node
return !voidNodeTags.contains(node.nodeName);
} else { //is not an element node
return false;
}
};
function getLastChildElement(el){
var lc = el.lastChild;
while(lc && lc.nodeType != 1) {
if(lc.previousSibling)
lc = lc.previousSibling;
else
break;
}
return lc;
}
//Based on Nico Burns's answer
cursorManager.setEndOfContenteditable = function(contentEditableElement)
{
while(getLastChildElement(contentEditableElement) &&
canContainText(getLastChildElement(contentEditableElement))) {
contentEditableElement = getLastChildElement(contentEditableElement);
}
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
}( window.cursorManager = window.cursorManager || {}));
希望这能如你所愿。