我正在获取用户从 html 页面中选择的文本。我正在数组中打印此文本的索引。
我有一段文字内容。获取所选文本的索引没有问题,同时选择不带点(.)的文本,
但是当选择带有点(.)的文本时索引值总是显示1。
例如,在下面的段落中
I am working in HTML with jquery. I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
当我选择“在 html 中工作”时,这在数组中看起来不错,并且索引打印为“5”。
但是当我选择“jquery。我想要”(有点)时。索引不可用(26)。
这是我的代码,https://jsfiddle.net/qL659gmh/7/
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">I am working in HTML with jquery.
I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
I am able to get the selected lines as follows using jquery,
</div>
<script type="text/javascript">
var arr = [];
$('#test').mouseup(function () {
var output='';
output += getSelectedText();
arr.push(output);
highlightSelected();
$('#result').html(output);
indx(output);
});
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
function indx(text){
inputText = document.getElementById("test")
var innerHTML = inputText.innerHTML
var index = innerHTML.indexOf(text);
console.log("innerHTML---------------"+innerHTML)
console.log("text---------------"+text)
console.log("index---------------"+index)
}
最佳答案
您需要使用 innerText
而不是 innerHtml
因为 document.selection.createRange().text
返回没有任何标记的纯文本,即放置在点(.) 之后的换行符上。更清楚地说,问题不是点(.),而是点(.)之后的新行,浏览器不显示
这是jsFiddle
关于javascript - 文档选择中的索引错误,而所选文本有一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34647985/