处理用户选择的片段(javascript)

时间:2014-01-19 09:50:55

标签: javascript range getselection

我有以下功能:

function manipulateSelection() {
        if (window.getSelection) {  // all browsers, except IE before version 9
        var selection = window.getSelection ();
        if (selection.rangeCount > 0) {
            var range = selection.getRangeAt (0);
            var fragment = range.extractContents();
            /*

            manipulate fragment here 

            */
            range.insertNode(fragment);
            selection.removeAllRanges();
            selection.addRange (range);
        }
        else alert("nothing selected");
    }
    else alert("browser not supported");
}

我想操纵用户所选文本的片段。但是,如果选择执行多个标记,则无需操作片段,我的代码就会中断。

例如:

<p>lorem i<selection>psum</p><p>dolor</selection> sit amet</p>

结果:

<p>lorem i</p><p>psum</p><p>dolor</p><p> sit amet</p>

虽然我希望它保持不变(如果我不操纵它)。

JS小提琴:http://jsfiddle.net/QebpX/1/

1 个答案:

答案 0 :(得分:0)

您可以先克隆范围并操纵克隆范围,然后将其插入选区(如果您已操纵它)

    function manipulateSelection() {
    if (window.getSelection) {  // all browsers, except IE before version 9
    var selection = window.getSelection ();
    if (selection.rangeCount > 0) {
        var range = selection.getRangeAt (0);

        var temp_range = range.cloneRange();
        var temp_fragment = temp_range.extractContents();
        /*
        manipulate fragment here 

        */
        if(manipulated)
        {
          var fragment = range.extractContent();
          range.insertNode(temp_fragment);
          selection.removeAllRanges();
          selection.addRange (range);
        }   
    }
    else alert("nothing selected");
  }
 else alert("browser not supported");

}