我在this post中发现了一段非常酷的代码,用于捕获用户在div中突出显示的所有文本。但是,在我的情况下,我想实际存储在div中选择的所有元素的元素id。我可以通过操作以下示例的输出(基于the earlier mentioned post)来做到这一点,但我希望有一种更优雅的方式直接检索所选元素?
firstOrNew

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;
}
$("#div_1").on("mouseup",function(){
console.dir(getSelectionHtml());
});
&#13;
答案 0 :(得分:0)
我在发布这个问题之后意识到我可以调整我用来获取答案的代码(因为原始代码我在选定的孩子中使用循环):
function getSelectionChildrenHtml() {
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());
var children = sel.getRangeAt(i).cloneContents().children;
}
}
}
return children;
}
$("#div_1").on("mouseup",function(){
console.dir(getSelectionChildrenHtml());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_1">
<span id="span_1">Span 1 text</span>
<span id="span_2">Span 2 text</span>
<span id="span_3">Span 3 text</span>
<span id="span_4">Span 4 text</span>
</div>