[英]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.