2

在这里,如果我在浏览器上选择了一些 3 或 4 行,那么我想要浏览器上的选择编号,即选择的计数 <span>

我有一个 example.html,其中包含以下代码,

<div id="p">
<p id="p1">
    <span>wefwef wefwefsdfc fcsdcs wefwscsdc qwefwcsdc </span>
    <span>wefwec acvsdc wecfsdc <br />asdcsdc sdcdc wedwed</span>
    <span> wefwec acvsdc wecfsdc asdcsdc sdcdc</span>
    <span> wefwec acvsdc wecfsdc<br /> asdcsdc sdcdc</span>
    <span>wefwec acvsdc wecfsdc asdcsdc sdcdc</span>
</p>
<p>
    <span>wefwef wefwefsdfc fcsdcs wefwscsdc qwefwcsdc </span>
    <span>wefwec acvsdc wecfsdc <br />asdcsdc sdcdc wedwed</span>
    <span> wefwec acvsdc wecfsdc asdcsdc sdcdc</span>
    <span> wefwec acvsdc wecfsdc<br /> asdcsdc sdcdc</span>
</p>
</div>

我有以下问题:

  1. 如何计算选中<span>
  2. 我将如何获得选择<span>
4

1 回答 1

1

您可以使用与此类似的代码获取所选内容的 HTML:

function getSelectedHTML () {
    var result = '';
    var range;
    if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        result = range.htmlText;
    }
    else if (window.getSelection) {
        var selection = window.getSelection();
        if (selection.rangeCount > 0) {
            range = selection.getRangeAt(0);
            var clonedSelection = range.cloneContents();
            var div = document.createElement('div');
            div.appendChild(clonedSelection);
            result = div.innerHTML;
        }
    }

    return result;
}

之后,就是解析选择的问题了。一种方法是使用 jQuery:

var count = $('span', $(getSelectedHTML())).length;
于 2013-09-10T09:23:06.030 回答