Tim*_*own 453
获取用户选择的文本相对简单.通过涉及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;
}
Run Code Online (Sandbox Code Playgroud)
如果您对同时处理选择<textarea>和texty <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();
};Run Code Online (Sandbox Code Playgroud)
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>Run Code Online (Sandbox Code Playgroud)
Par*_*Par 103
以这种方式获取高亮文本:
window.getSelection().toString()
Run Code Online (Sandbox Code Playgroud)
当然还有特殊待遇,即:
document.selection.createRange().htmlText
Run Code Online (Sandbox Code Playgroud)
Ebu*_*uka 11
使用window.getSelection().toString().
您可以在developer.mozilla.org上阅读更多内容
小智 10
如果您使用chrome(无法验证其他浏览器)并且文本位于同一DOM元素中,则此解决方案有效:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)
Run Code Online (Sandbox Code Playgroud)
MD *_*YON 10
如果需要,您可以使用事件
document.addEventListener('selectionchange', (e)=>{
console.log("Archor node - ",window.getSelection().anchorNode);
console.log("Focus Node - ",window.getSelection().toString());
});
Run Code Online (Sandbox Code Playgroud)
小智 6
是的,您可以使用简单的 JavaScript 代码段来实现:
document.addEventListener('mouseup', event => {
if(window.getSelection().toString().length){
let exactText = window.getSelection().toString();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
215167 次 |
| 最近记录: |