405

jQuery などを使用して、Web サイトの段落で強調表示されたテキストを取得することは可能ですか?

4

6 に答える 6

555

ユーザーが選択したテキストを取得するのは比較的簡単です。windowオブジェクトとオブジェクト以外は何も必要ないため、jQuery を使用しても得られるメリットはありませんdocument

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

<textarea>テキスト<input>要素での選択も処理する実装に興味がある場合は、次を使用できます。現在は 2016 年なので、IE <= 8 のサポートに必要なコードは省略していますが、SO の多くの場所にそのためのものを投稿しました。

function getSelectionText() {
    var text = "";
    var activeEl = document.activeElement;
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
    if (
      (activeElTagName == "textarea") || (activeElTagName == "input" &&
      /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
      (typeof activeEl.selectionStart == "number")
    ) {
        text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
    } else if (window.getSelection) {
        text = window.getSelection().toString();
    }
    return text;
}

document.onmouseup = document.onkeyup = document.onselectionchange = function() {
  document.getElementById("sel").value = getSelectionText();
};
Selection:
<br>
<textarea id="sel" rows="3" cols="50"></textarea>
<p>Please select some text.</p>
<input value="Some text in a text input">
<br>
<input type="search" value="Some text in a search input">
<br>
<input type="tel" value="4872349749823">
<br>
<textarea>Some text in a textarea</textarea>

于 2011-03-21T14:57:23.347 に答える
133

この方法で強調表示されたテキストを取得します。

window.getSelection().toString()

もちろん、次の場合の特別な処理:

document.selection.createRange().htmlText
于 2014-06-19T14:47:28.740 に答える
13

この解決策は、クロムを使用している場合 (他のブラウザーを確認できない場合) で、テキストが同じ DOM 要素にある場合に機能します。

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)
于 2012-03-20T20:02:13.930 に答える
1

必要に応じてイベントを使用できます

    document.addEventListener('selectionchange', (e)=>{
        console.log("Archor node - ",window.getSelection().anchorNode);
        console.log("Focus Node - ",window.getSelection().toString());
    });
于 2021-07-24T14:03:31.533 に答える