window.getSelection在Chrome中无法正常运行

时间:2018-09-22 17:10:05

标签: javascript google-chrome firefox range selection

我正在创建wysiswyg。我的编辑器应添加一个框,其中包含选定的文本和 其样式

我尝试查看window.getSelection()以获取选定的文本,然后在堆栈溢出时找到getSelectionHtml函数,并将其添加到我的代码中,如下所示。

我的问题是,如果所选文本具有某些样式(例如删除线),但window.getSelection()中不包含其样式。

这在Firefox中工作正常,但在Chrome中却不能。这是GIF中的示例。

在Chrome中(它不起作用,不包括样式):

enter image description here

在Firefox中(工作正常,包括样式):

enter image description here

我尝试在Chrome中进行测试,发现必须在所选文本和window上再选择一个字符。getSelection()将正确返回所选文本及其样式。例如,当编辑器中的文本为“ hello world 123”并且我需要选择其样式为“ world”时,我必须选择“ world ”(包括空格)以获取其风格。这是GIF中的示例。

enter image description here

能否请您提出我该如何解决这个问题?

function strikethrough() {
  document.execCommand('strikeThrough', false, '')
}

function addBox() {
  var html = getSelectionHtml()
  document.execCommand('insertHTML', false, '</br><div class="box">' + html + '</div></br>')
}

function getSelectionHtml() {
  var html = "";
  if (typeof window.getSelection != "undefined") {
    var sel = window.getSelection();
    if (sel.rangeCount) {
      var container = document.createElement("div");
      for (var i = 0, len = sel.rangeCount; i < len; ++i) {
        container.appendChild(sel.getRangeAt(i).cloneContents());
      }
      html = container.innerHTML;
    }
  } else if (typeof document.selection != "undefined") {
    if (document.selection.type == "Text") {
      html = document.selection.createRange().htmlText;
    }
  }
  return html
}
.box {
  border: 1px solid black;
}

.editor {
  width : 500px;
  height : 500px;
  border : 1px solid black;
  font-size:30px;
}
<button onclick="strikethrough()">strike through</button>
<button onclick="addBox()">add box</button><br><br>
<div class="editor" contenteditable><div>

0 个答案:

没有答案
相关问题