3

単語を 5 回含む文字列があります。hello を選択すると、4 が返されます。

 <div id="content">hello hai hello hello hello</div>

選択したテキスト スクリプトの取得

<script>
 if(window.getSelection){
   t = window.getSelection();
 }else if(document.getSelection){
   t = document.getSelection();
 }else if(document.selection){
   t =document.selection.createRange().text;
 }
 </script>

選択 haiしている場合は、 を返す必要があり1ます。

選択 hello haiしている場合は、 を返す必要があり1ます。助けてください。

4

2 に答える 2

9

の内容が単一のテキスト ノードであることが保証されていると仮定すると<div>、これはそれほど難しくありません。以下は、Selection API と Range API をサポートしていない IE < 9 では機能しません。これらのブラウザーのサポートが必要な場合は、この特定のケースのコードを提供するか、Rangyライブラリを使用できます。

ライブデモ: http://jsfiddle.net/timdown/VxTfu/

コード:

if (window.getSelection) {
    var sel = window.getSelection();
    var div = document.getElementById("content");

    if (sel.rangeCount) {
        // Get the selected range
        var range = sel.getRangeAt(0);

        // Check that the selection is wholly contained within the div text
        if (range.commonAncestorContainer == div.firstChild) {
            // Create a range that spans the content from the start of the div
            // to the start of the selection
            var precedingRange = document.createRange();
            precedingRange.setStartBefore(div.firstChild);
            precedingRange.setEnd(range.startContainer, range.startOffset);

            // Get the text preceding the selection and do a crude estimate
            // of the number of words by splitting on white space
            var textPrecedingSelection = precedingRange.toString();
            var wordIndex = textPrecedingSelection.split(/\s+/).length;
            alert("Word index: " + wordIndex);
        }
    }
}
于 2012-07-19T10:46:59.267 に答える
3

DOMのRange機能を使用する必要があります。現在選択されている範囲を取得する方法は次のとおりです。

var currentRange = window.getSelection().getRangeAt(0);

そこから currentRage.startOffset は、ファイル内の選択の位置を教えてくれます。したがって、それを要素の開始範囲と比較する必要があります。

var myContent = document.getElementById('content');
var divRange = document.createRange ();
divRange.selectNodeContents (myContent);

これで、divRange.startOffset を選択した startOffset と比較して、どちらにいるかを判断できます。

于 2012-07-19T10:23:19.853 に答える