Javascript 如何查找div的子节点元素;“内容可编辑”;光标正在输入事件处理程序上写入的位置
我试图创建一个自定义textarea编辑器,在div元素上添加contenteditable作为属性,文本将作为文本元素,hashtag将作为span元素,但问题是当我想在文本和hashtag之间添加一个hashtag时,必须找到光标正在写入的子元素的当前索引,然后我可以使用inderBefore方法在这个索引之后添加这个元素,谢谢 我的html代码:Javascript 如何查找div的子节点元素;“内容可编辑”;光标正在输入事件处理程序上写入的位置,javascript,angular,dom,dom-manipulation,Javascript,Angular,Dom,Dom Manipulation,我试图创建一个自定义textarea编辑器,在div元素上添加contenteditable作为属性,文本将作为文本元素,hashtag将作为span元素,但问题是当我想在文本和hashtag之间添加一个hashtag时,必须找到光标正在写入的子元素的当前索引,然后我可以使用inderBefore方法在这个索引之后添加这个元素,谢谢 我的html代码: <div class="text"> <div #textarea class="textarea" contente
<div class="text">
<div #textarea class="textarea" contenteditable="true"
(input)="onchangeText($event)" (focusin)="toggleFocus()" (focusout)="toggleFocus()" >
that is a post <span class="hashtag">#hashtag</span> try to add hashtag at the
<span class="hashtag">#beginig</span> will be add as last child to the and
</div>
<div class="placeholder" *ngIf="checkPlaceHolder()" (click)="onclickPlaceHolder($event)"
[ngStyle]="{opacity:focus? 0.5 : 1}">
What do you want to share?
</div>
</div>
这是我的加法:
onAddElement(text, type) {
this.removeLastCharacter();
if (type === "hash") {
// add element for hash tag
const span: HTMLParagraphElement = this.renderer.createElement("span");
span.innerHTML = text;
this.renderer.addClass(span, "hashtag");
this.renderer.appendChild(this.textarea.nativeElement, span);
//must use insertBefore method, but before it must find index of child elemenet where to add it
// this.renderer.insertBefore( this.textarea.nativeElement , p , this.textarea.nativeElement.children[1] );
} else if (type === "text") {
// add element for text
const textNode = this.renderer.createText("");
textNode.textContent = text;
this.renderer.appendChild(this.textarea.nativeElement, textNode);
}
this.setText();
this.setCursorToEnd();
}
以下是一个例子:
onAddElement(text, type) {
this.removeLastCharacter();
if (type === "hash") {
// add element for hash tag
const span: HTMLParagraphElement = this.renderer.createElement("span");
span.innerHTML = text;
this.renderer.addClass(span, "hashtag");
this.renderer.appendChild(this.textarea.nativeElement, span);
//must use insertBefore method, but before it must find index of child elemenet where to add it
// this.renderer.insertBefore( this.textarea.nativeElement , p , this.textarea.nativeElement.children[1] );
} else if (type === "text") {
// add element for text
const textNode = this.renderer.createText("");
textNode.textContent = text;
this.renderer.appendChild(this.textarea.nativeElement, textNode);
}
this.setText();
this.setCursorToEnd();
}