獲取突出顯示/選定的文本

是否有可能在網站的某個段落中得到突出顯示的文本,例如使用jQuery? html


#1樓

經過如下方式獲取突出顯示的文本: chrome

window.getSelection().toString()

固然對如下對象也有特殊待遇: 瀏覽器

document.selection.createRange().htmlText

#2樓

獲取用戶選擇的文本相對簡單。 涉及jQuery沒有任何好處,由於您只須要windowdocument對象便可。 ide

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>


#3樓

若是您使用的是chrome(沒法驗證其餘瀏覽器),而且文本位於同一DOM元素中,則此解決方案有效: url

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)
相關文章
相關標籤/搜索