光标在替换时卡在上标或下标中

时间:2018-07-11 06:24:30

标签: javascript html

我有两个按钮可以将所选文本转换为上标或下标。 当我将文本转换为上标时,我的光标停留在上标行高中,并且没有回到正常的行高,下标也出现了同样的错误。请有人帮助我解决此错误。 谢谢。

function getText(tag) {
  var text = document.getElementsByClassName("div-input")[0].innerHTML;
  console.log(text);
  var selected = "";
  if (window.getSelection) {
    selected = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control") {
    selected = document.selection.createRange().text;
  }
  var newnode = document.createElement(tag);
  var node = document.createTextNode(selected);
  newnode.appendChild(node);

  replaceSelectedText(newnode);
}

function replaceSelectedText(replacementText) {
  var sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      range.insertNode(replacementText);
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    range.text = replacementText;
  }
}
<html>

<head>
  <title>Question Paper Website</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="main.js"></script>
</head>

<body>
  <button class="superscript btn" onclick="getText('sup')">S<sup>2</sup></button>
  <button class="subscript btn" onclick="getText('sub')">S<sub>2</sub></button>
  <div contentEditable=true class="div-input" id="questionData" style="display:block;height:300px;width:300px;border:1px solid;"></div>
</body>

</html>

0 个答案:

没有答案