programing

강조 표시/선택한 텍스트를 가져옵니다.

bestcode 2022. 11. 17. 21:13
반응형

강조 표시/선택한 텍스트를 가져옵니다.

예를 들어 jQuery를 사용하여 웹 사이트의 단락에서 강조 표시된 텍스트를 얻을 수 있습니까?

사용자가 선택한 텍스트를 얻는 방법은 비교적 간단합니다.jQuery를 사용하여 얻을 수 있는 이점은 없습니다. 왜냐하면 다른 것은 필요 없기 때문입니다.window그리고.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>

강조 표시된 텍스트를 다음과 같이 가져옵니다.

window.getSelection().toString()

그리고 물론 다음과 같은 특별한 취급을 받는다.

document.selection.createRange().htmlText

이 솔루션은 크롬을 사용하는 경우(다른 브라우저를 확인할 수 없음), 텍스트가 동일한 DOM 요소에 있는 경우 작동합니다.

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)

사용하다window.getSelection().toString().

자세한 것은, developer.mozilla.org 를 참조해 주세요.

네, 간단한 JavaScript 스니펫으로 할 수 있습니다.

document.addEventListener('mouseup', event => {  
    if(window.getSelection().toString().length){
       let exactText = window.getSelection().toString();        
    }
}

원하는 경우 이벤트를 사용할 수 있습니다.

    document.addEventListener('selectionchange', (e)=>{
        console.log("Archor node - ",window.getSelection().anchorNode);
        console.log("Focus Node - ",window.getSelection().toString());
    });

언급URL : https://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text

반응형