如何找到光标在输入事件处理程序上编写的div“ contenteditable”的子节点元素

时间:2019-12-13 15:34:07

标签: javascript angular dom dom-manipulation

我试图通过将contenteditable作为属性添加到div元素上来创建自定义textarea编辑器,该文本将作为text元素,而hashtag将作为span元素,但是问题是当我想在文本之间添加hashtag时和hashtag,为此必须找到光标正在写入的子元素的当前索引,然后我可以使用inderBefore方法在此索引之后添加该元素

我的html代码:

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

这是我的输入事件处理程序:

onchangeText(event) {
   // on input event handler

   if (this.isAfterHashtag()) {
      this.onAddElement(event.data, "text"); //add new element
   }

   if (this.isHashtag(event.data)) {
     // if character is # hashtag

     this.onAddElement(event.data, "hash");
   }

   this.setText();

   if (this.checkPlaceHolder()) {// if the length of textare is 0

     this.textarea.nativeElement.innerHTML = "";
   }
}

这是我的addElementMethod:

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();
}

这是一个示例:

custom textarea editor

0 个答案:

没有答案