Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

javascript - 获取突出显示/选定的文本(Get the Highlighted/Selected text)

是否有可能在网站的某个段落中获得突出显示的文本,例如使用jQuery?

  ask by Dan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Getting the text the user has selected is relatively simple.

(获取用户选择的文本相对简单。)

There's no benefit to be gained by involving jQuery since you need nothing other than the window and document objects.

(涉及jQuery没有任何好处,因为您只需要windowdocument对象即可。)

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;
}

If you're interested in an implementation that will also deal with selections in <textarea> and texty <input> elements, you could use the following.

(如果您对同时处理<textarea>和文本<input>元素中的选择的实现感兴趣,则可以使用以下内容。)

Since it's now 2016 I'm omitting the code required for IE <= 8 support but I've posted stuff for that in many places on SO.

(因为现在是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> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...