【问题标题】:Get parent element of beginning (and end) of selected text获取所选文本开头(和结尾)的父元素
【发布时间】:2015-09-11 03:53:24
【问题描述】:

假设我有这个 HTML

<div id="someparent">
     Foo
     <span id="one">Selection starts anywhere inside here</span>
     <span id="two">Selection ends anywhere inside here</span>
     <span id="three">Some more text here</span>
     Bar
</div>

我想返回跨度#one 和跨度#two 节点(这样我就可以在它们周围再包裹一个跨度*)。如果 foo 和 bar 是选择的起点和终点,则会返回 div #someparent(两次)。

*即使使用 jQuery,如何做到这一点也会很有帮助。

这类似于this question which asks for the single parent of the whole selected text

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    此代码将返回选择的开始和结束的父节点:

    var getSelectionParents=function(){
        var selection=document.getSelection();
        if(!selection.toString().length)
            return false;
        else
            return {
                start:selection.anchorNode.parentNode,
                end:selection.focusNode.parentNode
            };
    }
    
    document.addEventListener('mouseup',function(){
        console.log(getSelectionParents());
    });
    

    下面是运行代码的 JSFiddle:http://jsfiddle.net/jaredcrowe/wh1p3ncu/

    【讨论】:

    • 这似乎运作良好。是跨浏览器吗?它在IE中工作吗? (我不担心支持旧版本,主要是 IE9 及更高版本)。
    • 是的,我刚刚测试了我在 IE9 和 IE11 中提供的 JSFiddle,它似乎在两者中都可以工作。
    • 如果您愿意看的话,这里有一个后续问题 :-) stackoverflow.com/questions/32557516/…
    【解决方案2】:

    我认为你可以使用范围来做到这一点

    $('button').click(function() {
      var selection = document.getSelection();
    
      var start = selection.getRangeAt(0);
      snippet.log('start: ' + start.startContainer.parentNode.id);
      snippet.log('end: ' + start.endContainer.parentNode.id);
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
    <div id="someparent">
      Foo
      <span id="one">Selection starts anywhere inside here</span>
      <span id="two">Selection ends anywhere inside here</span>
      <span id="three">Some more text here[enter link description here][1]</span>
      Bar
    </div>
    <button>test</button>

    注意:Not supported in IE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 2011-11-05
      • 2011-07-26
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      相关资源
      最近更新 更多