是否有可能得到突出显示的文本在一个网站的一个段落,例如使用jQuery?
当前回答
这个解决方案工作,如果你使用chrome(不能验证其他浏览器),如果文本位于相同的DOM元素:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)
其他回答
使用window.getSelection () .toString()。
你可以在developer.mozilla.org上阅读更多
用这种方式高亮显示文本:
window.getSelection().toString()
当然,还有对ie的特殊处理:
document.selection.createRange().htmlText
如果需要,可以使用事件
document.addEventListener('selectionchange', (e)=>{
console.log("Archor node - ",window.getSelection().anchorNode);
console.log("Focus Node - ",window.getSelection().toString());
});
是的,你可以用简单的JavaScript代码片段:
document.addEventListener('mouseup', event => {
if(window.getSelection().toString().length){
let exactText = window.getSelection().toString();
}
}
这个解决方案工作,如果你使用chrome(不能验证其他浏览器),如果文本位于相同的DOM元素:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)