![](/img/trans.png)
[英]Insert text at the caret position, inside a contenteditable body of a frame
[英]Insert text at caret position Contenteditable : Angular 8
我有一個 contenteditable div,當我試圖在那個 div 中粘貼一些文本時,它總是被粘貼到最后。 我正在使用 view child 來訪問 contenteditable div 的引用,並使用內部文本來獲取值。
問題我怎樣才能將復制的文本粘貼到當前 cursor position。
請在下面找到我的代碼。
組件.html
<div class="text-block" contenteditable #textBlockElement (input)="textOnChange($event.target.innerText)" (paste)="pasteOnContenteditable($event)"></div>
組件.ts
@ViewChild('textBlockElement ', { static: false }) textBlockElement : ElementRef;
pasteOnContenteditable(e : any) {
e.preventDefault();
let clipboardData = e.clipboardData;
let pastedText = clipboardData.getData('text');
let textEl : HTMLElement = this.textBlockElement.nativeElement;
textEl.innerText = textEl.innerText + pastedText;
}
textOnChange(textVal : string){
console.log(textVal);
}
我已經嘗試了您的方案並找出了您的邏輯行為錯誤的地方。
您的代碼中的問題是您在末尾附加了文本,而不是找到 cursor position。
請檢查以下代碼以解決您的問題。 ( https://stackblitz.com/edit/angular-ivy-pnjtxp?file=src%2Fapp%2Fapp.component.html )
在 app.component.html
<div class="text-block" contenteditable #textBlockElement
(input)="textOnChange($event.target)"
(paste)="pasteOnContenteditable($event)"></div>
在 app.component.ts 中
import { Component, VERSION, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
@ViewChild('textBlockElement ', { static: false }) textBlockElement : ElementRef;
pasteOnContenteditable(e : any) {
e.preventDefault();
let clipboardData = e.clipboardData;
let pastedText = clipboardData.getData('text');
let textEl : HTMLElement = this.textBlockElement.nativeElement;
// textEl.innerText = textEl.innerText + pastedText;
this.insertAtCursor(textEl, pastedText);
}
insertAtCursor (input, textToInsert) {
// get current text of the input
const value = input.innerText;
console.log('***********',value);
// save selection start and end position
const start = input.selectionStart;
const end = input.selectionEnd;
// update the value with our text inserted
input.innerText = value.slice(0, start) + textToInsert + value.slice(end);
// update cursor to be at the end of insertion
input.selectionStart = input.selectionEnd = start + textToInsert.length;
}
textOnChange(textVal){
console.log(textVal);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.