获取选定内容中特定类的开始节点和结束节点

  • 本文关键字:节点 开始 结束 获取 jquery
  • 更新时间 :
  • 英文 :


我正在尝试弄清楚如何在用户选择的文本中获取特定类的第一个和最后一个节点。例如,请考虑以下 HTML。几个跨度设置为类"壁画"。

<p>
If he tries coming to first <span class="fresca">he will be called</span> for a
balk. Some pitchers will cross over their right knee but not cross
their right foot.
</p>
<p>
A pitcher <span class="fresca">must get</span> to a set position, where
he comes to a <span class="fresca">complete stop</span> after he gets
the sign but before he starts his motion home.
</p>
<p>
A pitcher's <span class="fresca">right foot</span>
must go in the general direction he is throwing.
</p>

例如,如果用户选择"投手必须到达设定的位置,在他到达后他会完全停止",那么我的脚本将获得对跨度"必须得到"和跨度"完全停止"的引用。

如果用户选择"脚必须走",那么我的脚本会得到两个对跨度"右脚"的引用(或者可能只有一个引用(。

如果用户选择不包含任何"fresca"跨度的内容,那么我的脚本只会得到一个 null(或者可能是两个 null 的数组(。

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;
}
$(function() {
$(document).on("mouseup",'.select-area', function() {
// getting the selected html
var mytext = getSelectionHtml();
// parse it as html
myhtml = $.parseHTML(mytext);
// writing to temporary block
$('#tmp').html(myhtml);
// getting fresca elements
var elements = $('#tmp').find('.fresca');
var texts = new Array();
elements.each(function(){
// Pushing into texts
texts.push($(this).html());
}) 
console.log(texts);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-area">
<p>
If he tries coming to first <span class="fresca">he will be called</span> for a
balk. Some pitchers will cross over their right knee but not cross
their right foot.
</p>
<p>
A pitcher <span class="fresca">must get</span> to a set position, where
he comes to a <span class="fresca">complete stop</span> after he gets
the sign but before he starts his motion home.
</p>
<p>
A pitcher's <span class="fresca">right foot</span>
must go in the general direction he is throwing.
</p>
</div>
<hr/>
<div style="display:none" id="tmp"></div>

在这个问题的帮助下,我写了这个答案。试试吧。

最新更新