【问题标题】:Saving highlighted text to a string将突出显示的文本保存到字符串
【发布时间】:2018-01-16 19:13:48
【问题描述】:
我正在制作一个将屏幕分成两个窗口的 Web 应用程序,一侧是基于 Web 的文本编辑器,另一侧只是一个普通窗口。
我正在尝试找到一种方法,让用户能够在浏览器端突出显示某些文本,然后将突出显示的文本自动保存到一个字符串中,然后我就可以在其中操作该字符串。
有人有什么想法吗?任何帮助将不胜感激。
【问题讨论】:
标签:
javascript
html
web-applications
highlight
【解决方案1】:
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;
}
$(document).ready(function (){
$('div').mouseup(function (e){
alert(getSelectionText())
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Hello, this is a highlight text test
</div>
【解决方案2】:
所以这里有两个步骤。
- 捕获 mouseup 事件。
- 返回选定的文本。
在文档上选择的任何文本都可以通过 js 调用访问:
window.getSelection()
但这是特定于浏览器的。因此,您可以使用此代码 sn-p 来覆盖从所有浏览器中获取选定的文本。
function getSelectedText () {
var txt = ''
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
return txt;
}
我假设您正在使用像 jQuery 这样的库。这样可以帮助处理 mouseup 事件。您可能不想捕获整个文档的选择。所以你可以绑定到你需要的任何元素。像我的 jsfiddle 在这里:http://jsfiddle.net/xh799/