如何在JavaScript的DIV中从范围的开头和结尾获取innerHTML

时间:2018-08-06 14:38:06

标签: javascript

如何从父级DIV获取innerHTML,innerHTML停在所选单词处?

类似的示例,如果选择了“ asx”一词,我将得到This select some <b>is a <i>some的结果警报innerHTML。

谢谢

function selected(element) {
    var start = '';
    var end = '';
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;
    var sel;
    if (typeof win.getSelection != "undefined") {
        sel = win.getSelection();
        if (sel.rangeCount > 0) {
            var range = win.getSelection().getRangeAt(0);
            
            var preCaretRange = range.cloneRange();

            preCaretRange.selectNodeContents(element);

            preCaretRange.setEnd(range.startContainer, range.startOffset);

            var start = preCaretRange.toString();

            alert(start);

        }
    } 

}
<div id="editor" contenteditable="true">This select some <b>is a <i>some asx</i> sdc</b> select some text in some here.</div>
<button type="button" onclick="selected(document.querySelector('#editor'))">edit</button>

1 个答案:

答案 0 :(得分:0)

不可能让innerHTML“停止”在一个词上。但是,可以通过编辑 innerHTML 的字符串输出来更改警报内容。

function selected(element) {
  var sel;
  if (typeof window.getSelection != "undefined") {
    sel = window.getSelection();
    if (sel.rangeCount > 0) {
      var range = window.getSelection().getRangeAt(0);
      var preCaretRange = range.cloneRange();
      preCaretRange.selectNodeContents(element);
      preCaretRange.setEnd(range.startContainer, range.startOffset);
      var start = preCaretRange.toString();
      alert(start.split("asx")[0]);
    }
  }
}
<div id="editor" contenteditable="true">This select some <b>is a <i>some asx</i> sdc</b> select some text in some here.</div>
<button type="button" onclick="selected(document.querySelector('#editor'))">edit</button>