我有一个div:
<div>Lorem ipsum dolor sit amet, <b>consectetur adipiscing elit.</b> Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo.</div>
when I just click in the area betwen the 2 Bold balises <b></b>, I want to create a selection of whole area.
我测试:
var sel = window.getSelection();
if (sel.rangeCount == 0) {
return false;
}
var range = sel.getRangeAt(0);
var object = range.commonAncestorContainer.nodeName === '#text'? range.commonAncestorContainer.parentElement: range.commonAncestorContainer;
range.setStart(object,0);
len = object.innerHTML.length;
range.setEnd(object, len);
但选择并不好。它设置位置0到我在div中的点击位置,而不是在字符串的末尾
你有解决方案吗?感谢
答案 0 :(得分:0)
如果我理解你的要求,我认为你正在寻找这个:
尝试使用object。 childNodes .length;而不是object.innerHTML.length。您可以参考setEnd()文档here。
var sel = window.getSelection();
if (sel.rangeCount == 0) {
return false;
}
var range = sel.getRangeAt(0);
var object = range.commonAncestorContainer.nodeName === '#text'? range.commonAncestorContainer.parentElement: range.commonAncestorContainer;
range.setStart(object,0);
len = object.childNodes.length;
range.setEnd(object, len);