使用JavaScript对所选内容应用上标

Apply superscript to the selection using JavaScript

本文关键字:应用 上标 JavaScript 使用      更新时间:2023-09-26

有人能帮助我如何使用javascript将上标应用于内容可编辑div中的选择吗?

我有这个div和一个按钮:

<div contenteditable="true">Apple Grapes Orange</div>
<input type="button" onclick="applySuperScript" value="Apply SuperScript">

假设我已经从我的内容可编辑div中选择了文本"Orange"并点击按钮,那么应该调用javascript来为文本"Orage"应用超级脚本。

对html进行轻微修改。

<div id='text' contenteditable="true">Apple Grapes Orange</div>
<input type="button" id='super'  value="Apply SuperScript">

这是我们的点击处理程序

document.getElementById('super').onclick = function() {
 var textarea = document.getElementById('text');
 var anchorOffset = window.getSelection().anchorOffset;
 var focusOffset = window.getSelection().focusOffset;
 var str = textarea.innerHTML.substring(anchorOffset,focusOffset)
 textarea.innerHTML= textarea.innerHTML.replace(str,'<sup>'+str+'</sup>');
 };

这是小提琴。