我可以使用 window.getSelection() 选择文本。如何获取 HTML 代码中选择的开始和结束的字符位置?所以这个信息可以保存到服务器上。
最佳答案
我觉得没有内置函数来获取选择代码的开始和结束位置。你需要编写一些 JS 代码来获取这些位置。我只写了简单的代码。我不确定它是否有用。但是,请检查一下。
<html>
<head>
<script>
function GetSelectedText ()
{
var fullString = "I feel there is no built-in functions for getting start and end position of selection code. you need to write some JS coding for getting these position. I've wrote just simple coding. I'm not sure whether it will be useful or not. But, check it out.";
if (window.getSelection)
{
var range = window.getSelection ();
var startPosition = fullString.search(range);
var getPosition = range.toString();
var endPosition = parseInt(getPosition.length) + parseInt(startPosition)
alert ("Start position : " + startPosition + " and End position : " + endPosition);
}
else
{
if (document.selection.createRange)
{
var range = document.selection.createRange ();
var startPosition = fullString.search(range.text);
var getPosition = range.text;
var endPosition = parseInt(getPosition.length) + parseInt(startPosition);
alert ("Start position : " + startPosition + " and End position : " + endPosition);
}
}
}
</script>
</head>
<body>
<button onclick="GetSelectedText ()">
Get
</button>
I feel there is no built-in functions for getting start and end position of selection code. you need to write some JS coding for getting these position. I've wrote just simple coding. I'm not sure whether it will be useful or not. But, check it out.
</body>
</html>
对于此编码,您需要在两个位置定义文本消息。一是在JS编码
var fullString = "??"
另一个是按钮下面的正文消息/
关于javascript - 使用 JavaScript 保存 HTML 中突出显示的文本位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3438524/