0

選択したテキストをスパン内に配置して、CSSで背景色を与えるこのコードがあります。2つの異なるdivからのテキスト、または任意の2つのタグ内にあるテキストを「マーク」しようとすると、エラーが発生します。 Uncaught Error: BAD_BOUNDARYPOINTS_ERR: DOM Range Exception 1

これは私のコードです:

function highlightSelection()   {
var selection;



//Get the selected stuff
    if(window.getSelection) 
        selection = window.getSelection();
    else if(typeof document.selection!="undefined")
        selection = document.selection;

    //Get a the selected content, in a range object
    var range = selection.getRangeAt(0);

    //If the range spans some text, and inside a tag, set its css class.
    if(range && !selection.isCollapsed)
    {
            var span = document.createElement('span');
            span.className = 'highlight-green';
            range.surroundContents(span);
    }
}

HighlightSelection()はonmouseupイベントとともに呼び出されます。よろしくお願いします!

4

1 に答える 1

1

RangeのsurroundContents()方法は、Rangeのコンテンツを単一のノード内で囲むことができる場合にのみ機能します。例を見るとかなり直感的です。したがって、中括弧が範囲の境界を示す場合、以下は問題ありません。

One {two} three
One {two <b>three</b> four} five

...以下はOKではありませんが:

One {two <b>three} four</b> five
One <b>two {three</b> <i>four} five</i>

Insetad、document.execCommand()選択範囲に背景色を適用するために使用することをお勧めします。これにより、これらすべてが処理されます。以前、StackOverflowでこれを行うためのコードを提供しました。

代わりにクラスを適用する必要がある場合は、私のRangyライブラリのCSSクラスアプライヤーモジュールを使用できます。

于 2012-11-30T15:02:33.053 に答える