我可以使用window.getSelection()选择文本如何在HTML代码中获取选择的开头和结尾的字符位置?因此,此信息可以保存到服务器。
答案 0 :(得分:2)
我觉得没有用于获取选择代码的开始和结束位置的内置函数。你需要写一些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 =“??”
另一个是Button /
下面的Body消息答案 1 :(得分:0)
我认为较短的方法是使用javascript的string.indexOf()函数。它只返回较大字符串中搜索字符串的起始索引,如果不存在则返回-1。可以通过将子字符串的长度与起始索引相加来计算结束索引。
答案 2 :(得分:0)
根据文档的原始HTML源,您无法可靠地获取用户选择的偏移量。您只能根据节点内的节点和偏移量来获取它。我建议您查看类似问题的以下答案:Calculating text selection offsets in nest elements in Javascript