获取突出显示/选定的文本

是否有可能在网站的某个段落中得到突出显示的文本,例如使用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)
相关文章
相关标签/搜索