我对JS / JQUERY很新,并且花了最近两天试图解决这个问题。
我有下面的代码,但是当用户输入时,它会将插入符号带回DIV的开头。我需要插入位置保持用户上次输入的位置。我见过很多类似的帖子,但似乎没有一个与JQUERY合作......或者我可能没做对......(可能)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title> TEST</title>
<style>
div.input1
{
background-color:#eee;
border: 1px solid black;
margin:5px;
width:750px;
height:20px;
}
</style>
<script type='text/javascript'>
$(window).load(function()
{
var wrapwords = function()
{
$('#editor > div').each(function()
{
//--------------------Problem is here------------------------
var s=window.getSelection();
var sr=s.getRangeAt(0);
console.log("1",s.anchorOffset+" "+s.focusOffset,sr);
$(this).html($(this).text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
//s.removeAllRanges();
//s.addRange(sr);
console.log("2",s.anchorOffset+" "+s.focusOffset,sr);
//--------------------Problem is here------------------------
});
$('#editor span').hover(function()
{
$('#word').text($(this).css('background-color','#ffff66').text());
},
function()
{
$('#word').text('');
$(this).css('background-color','');
});
};
$('#editor').on('keyup', function()
{
wrapwords();
});
});
</script>
<script type='text/javascript'>
//-------------------------------------------------Text Box Length Start------------------------------------
$(document).ready(function()
{
var excempt = [37,38,39,40,46,8,36,35]; // Excempt keys(arrows, del, backspace, home, end);
$("[contenteditable='true']").each(function(index,elem) // Loop through every editiable thing
{
var $elem = $(elem); // Check for a property called data-input-length="value" (<div contenteditiable="true" data-input-length="100">)
var length = $elem.data('input-length'); // Validation of value
if(!isNaN(length)) // Register keydown handler
{
$elem.on('keydown',function(evt) // If the key isn't excempt AND the text is longer than length stop the action.
{
if(excempt.indexOf(evt.which) === -1 && $elem.text().length > length)
{
evt.preventDefault();
return false;
}
});
}
});
});
//-------------------------------------------------Text Box Length End---------------------------------------
</script>
<script>
var update = function() {
$('#caretposition').html(getCaretPosition(this));
};
$('#editable').on("mousedown mouseup keydown keyup", update);
</script>
</head>
<body>
<div contenteditable="true" class="input1" id="editor" data-input-length="100"><div> These are words</div></div><br>
Current word: <span id="word"></span>
</body>
</html>
答案 0 :(得分:0)
这是一种有效的产品。它可能会使用一些微调,但它的功能。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="//code.jquery.com/jquery-3.1.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Test</title>
<style>
div.input1
{
background-color:#eee;
border: 1px solid black;
margin:5px;
width:750px;
height:20px;
}
</style>
<script type='text/javascript'>
$(window).load(function()
{
//------------------Global Variables Start----------------------
var saveSelection, restoreSelection;
var divSelection;
var editable = $("#editor")[0];
var excempt = [37,38,39,40,46,8,36,35];
//------------------Global Variables End------------------------
//-------------------Highlight words Start----------------------Thank you: Grant Gibson (Stack Overflow)
var wrapwords = function()
{
$('#editor > div').each(function()
{
$(this).html($(this).text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
//console.log($(this).html()); //Words
});
$('#editor span').hover(function()
{
$('#word').text($(this).css('background-color','#ffff66').text());
//console.log($('#word').text()); //Selected Word
},
function()
{
$('#word').text('');
$(this).css('background-color','');
});
};
$('#editor').on('keyup', function()
{
divSelection = saveSelection(editable);
wrapwords();
restoreSelection(editable, divSelection);
});
wrapwords();
//-------------------Highlight words End------------------------Thank you: Grant Gibson (Stack Overflow)
//-------------------Save Cursor Position Start --------------- Thank you: Tim Down (Stack Overflow)
if (window.getSelection && document.createRange)
{
saveSelection = function(containerEl)
{
var doc = containerEl.ownerDocument, win = doc.defaultView;
var range = win.getSelection().getRangeAt(0);
var preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(containerEl);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
var start = preSelectionRange.toString().length;
return {
start: start,
end: start + range.toString().length
}
};
restoreSelection = function(containerEl, savedSel)
{
var doc = containerEl.ownerDocument, win = doc.defaultView;
var charIndex = 0, range = doc.createRange();
range.setStart(containerEl, 0);
range.collapse(true);
var nodeStack = [containerEl], node, foundStart = false, stop = false;
while (!stop && (node = nodeStack.pop()))
{
if (node.nodeType == 3)
{
var nextCharIndex = charIndex + node.length;
if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex)
{
range.setStart(node, savedSel.start - charIndex);
foundStart = true;
}
if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex)
{
range.setEnd(node, savedSel.end - charIndex);
stop = true;
}
charIndex = nextCharIndex;
}
else
{
var i = node.childNodes.length;
while (i--)
{
nodeStack.push(node.childNodes[i]);
}
}
}
var sel = win.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
else if (document.selection)
{
saveSelection = function(containerEl)
{
var doc = containerEl.ownerDocument, win = doc.defaultView || doc.parentWindow;
var selectedTextRange = doc.selection.createRange();
var preSelectionTextRange = doc.body.createTextRange();
preSelectionTextRange.moveToElementText(containerEl);
preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange);
var start = preSelectionTextRange.text.length;
return {
start: start,
end: start + selectedTextRange.text.length
}
};
restoreSelection = function(containerEl, savedSel)
{
var doc = containerEl.ownerDocument, win = doc.defaultView || doc.parentWindow;
var textRange = doc.body.createTextRange();
textRange.moveToElementText(containerEl);
textRange.collapse(true);
textRange.moveEnd("character", savedSel.end);
textRange.moveStart("character", savedSel.start);
textRange.select();
};
}
//-------------------Save Cursor Position End --------------- Thank you: Tim Down (Stack Overflow)
//-------------------Max Text Length Start------------------- Thank you: Tschallacka (Stack Overflow)
$("[contenteditable='true']").each(function(index,elem) // Loop through every editiable thing
{
var $elem = $(elem); // Check for a property called data-input-length="value" (<div contenteditiable="true" data-input-length="100">)
var length = $elem.data('input-length'); // Validation of value
if(!isNaN(length)) // Register keydown handler
{
$elem.on('keydown',function(evt) // If the key isn't excempt AND the text is longer than length stop the action.
{
if(excempt.indexOf(evt.which) === -1 && $elem.text().length > length)
{
evt.preventDefault();
return false;
}
});
}
});
//-------------------Max Text Length End------------------- Thank you: Tschallacka (Stack Overflow)
//---------------------------------------------------------
});
</script>
</head>
<body>
<div contenteditable="true" class="input1" id="editor" data-input-length="120"><div id="main">
These are words
</div>
</div><br>
Current word: <span id="word"></span>
</body>
</html>