我正在突出显示用户在html页面中选择的文本。
为此,我得到的值是用户通过拖动鼠标选择单词。我将它们放在数组onmouseup函数中。
单击按钮时,我正在突出显示。但是我不能突出显示正确的位置,单词被突出显示但是位置错误。
该单词在该div中出现4次,即使我选择了第4个单词,它也始终突出显示第一个单词。
这是我的代码,这是什么问题。
<html>
<head>
<style>
textarea {
width:100%;
height:150px;
}
.hilited1 {
background:red;
color:#fff;
}
.highlight
{
background-color:yellow;
}
</style>
</head>
<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 = [];
function go()
{
for (var i = 0; i < arr.length; i++) {
highlight(arr[i]);
}
}
function highlight(text)
{
inputText = document.getElementById("test")
var innerHTML = inputText.innerHTML
var index = innerHTML.indexOf(text);
if ( index >= 0 )
{
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length);
inputText.innerHTML = innerHTML
}
}
$('#test').mouseup(function () {
var output='';
output += getSelectedText();
arr.push(output);
});
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
</script>
<button onclick="go()">Highlight</button>
</body>
</html>
最佳答案
改变你的功能
$(document).on("mouseup", function (e) {
var selected = getSelection();
var range = selected.getRangeAt(0);
console.log(range);
if(selected.toString().length > 1){
var newNode = document.createElement("span");
newNode.setAttribute("class", "red");
range.surroundContents(newNode);
}
selected.removeAllRanges();
});
function getSelection() {
var seltxt = '';
if (window.getSelection) {
seltxt = window.getSelection();
} else if (document.getSelection) {
seltxt = document.getSelection();
} else if (document.selection) {
seltxt = document.selection.createRange().text;
}
else return;
return seltxt;
}
的HTML
<h3>hello world! hello world! hello world</h3>
<div>hello world! hello world hello world!</div><span>hello world! hello world</span>
的CSS
.red{color:red;}
http://jsfiddle.net/bZb7V/27/