如何从父级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>
答案 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>