html - 选择范围 - 获取范围+起始节点+结束节点+距离

时间:2010-06-02 05:38:36

标签: javascript html select range dhtml

从我的previous question中选择特定的html文字,我已经通过this link了解html字符串中的范围。

用于在html页面上选择特定文本。我们需要遵循这些步骤。

假设HTML:

<h4 id="entry1196"><a
    href="http://radar.oreilly.com/archives/2007/03/call_for_a_blog_1.html"
    class="external">Call for a Blogger's Code of Conduct</a></h4>

<p>Tim O'Reilly calls for a Blogger Code of Conduct. His proposals are:</p>

<ol>
    <li>Take responsibility not just for your own words, but for the
        comments you allow on your blog.</li>
    <li>Label your tolerance level for abusive comments.</li>
    <li>Consider eliminating anonymous comments.</li>
</ol>

通过范围进行选择的java脚本

var range = document.createRange();  // create range
var startPar = [the p node];         // starting parameter 
var endLi = [the second li node];    // ending parameter
range.setStart(startPar,13);         // distance from starting parameter.
range.setEnd(endLi,17);              // distance from ending parameter
range.select();                      // this statement will make selection

我想以反转的方式做到这一点。我的意思是,假设用户在浏览器上进行选择(safari)。我的问题是,我们怎样才能获得起始节点(因为我们在这里'p节点')和结束节点(因为我们这里有'第二个li节点')和范围(因为我们这里有13,17) ?

编辑:我的努力(来自this question

    var sel = window.getSelection();

    if (sel.rangeCount < 1) {
        return;
    }
    var range = sel.getRangeAt(0);
    var startNode = range.startContainer, endNode = range.endContainer;

    // Split the start and end container text nodes, if necessary
    if (endNode.nodeType == 3) {
        endNode.splitText(range.endOffset);
        range.setEnd(endNode, endNode.length);
    }

    if (startNode.nodeType == 3) {
        startNode = startNode.splitText(range.startOffset);
        range.setStart(startNode, 0);
    }

但是,如果被选中是第一段或第二或第三段,或者被选中的是第一个标题或第二个标题或者什么......我感到很困惑。

1 个答案:

答案 0 :(得分:6)

存储所选范围很简单。以下内容仅返回第一个选定范围(Firefox至少支持多个选择):

<script type="text/javascript">

function getSelectionRange() {
    var sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection) {
        return document.selection.createRange();
    }
    return null;
}

var range;

</script>
<input type="button" onclick="range = getSelectionRange();"
    value="Store selection">

range将具有属性startContainer(包含范围起点的节点),startOffset(起始容器节点内的偏移量:文本节点中的字符偏移量)和元素中的子偏移量,endContainerendOffset(相当于开始属性的behvaiour)。 its specificationMDC详细记录了Range

在IE中,range将包含TextRange,其工作方式非常不同。 TextRanges不是节点和偏移,而是关注字符,单词和句子。 Microsoft的网站有一些文档:http://msdn.microsoft.com/en-us/library/ms533042%28VS.85%29.aspxhttp://msdn.microsoft.com/en-us/library/ms535872%28VS.85%29.aspx

相关问题