![](/img/trans.png)
[英]How to detect cursor position in contenteditable div and insert text at that position
[英]insert bold tag in cursor position of div contenteditable
我有一個內容可編輯的 div 和一個事件,每次我輸入“@”時都會觸發一個事件,當我從下拉列表中選擇標記的人時,我會在 carret position 的 div 值中自動完成全名,我想將它添加到標簽中,但在我這樣做之后,它堅持用粗體書寫。 插入節點后,我如何 go 恢復正常寫入
這是插入標簽的 function:
insertTagInDiv(val: string): void {
const range = window.getSelection()?.getRangeAt(0);
const newElement = document.createElement("b");
newElement.innerHTML = val;
range?.deleteContents();
range?.insertNode(newElement);
}
模板非常簡單:
<div class="chat-action-container">
<div
ref="roomTextarea"
class="chat-text"
contenteditable
data-test="chat-text-area"
@input="onInput"
></div>
<OperationChatUserTagPanel
ref="userTagList"
:current-taggable-user="currentTaggableUser"
:is-tagging="isTaggingUser"
:last-at-coordinates="lastAtCoordinates"
:message="message"
:taggable-users="getTaggableUserList"
@set-tag-user="setActive"
@tag-user="tagUser"
/>
<div class="chat-actions">
<div
class="chat-send-action"
data-test="send-message-button"
@click="sendMessage"
>
Envoyer
</div>
</div>
</div
和 function 標記(我想在可編輯的 div 中插入樣式標記是:
tagUser(id: string): void {
const user = this.chatMembers.find(
(member) => member.id === id
) as TaggableUser;
const remainingChunkAfterCurrentTag = this.message.slice(
this.getCaretCharOffset(),
this.message.length
);
this.message =
this.message.substring(0, this.lastAtIndex) +
`@${user.firstName} ${user.lastName} ${remainingChunkAfterCurrentTag} `;
this.getTextareaRef.innerText = this.message;
this.setCaretPosition();
this.taggingUser = false;
}
我認為理解您的問題的關鍵是您將文本插入到可內容編輯的 div 中。 老實說,它們很難使用,而不是我在閱讀您的原始問題時所期望的。 這是我想出的解決方案: codesandbox 。
代碼框是您的代碼的一個非常簡化的版本,只是專注於將粗體文本插入到內容可編輯的 div 中,而其他文本仍然使用正常的字體樣式。
關鍵是將插入的文本與 div 的 rest 隔離開來,方法是將其放入自己的 div 中,使用contenteditable=false
。 我還必須使用display: inline-block
確保它與文本的 rest 保持一致。 此解決方案可能需要更多工作才能滿足 100% 的特定應用程序要求,但希望能幫助您接近所需的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.