I am pretty new to JavaScript and hope someone here can help me with the following:
Primarily looking for a solution in IE 8 - if it can cover other browsers / versions even better.
I have a page with only one contenteditable div that is created dynamically and contains both text and HTML tags.
On the page I want to add a button that inserts certain text at the cursor position into this div.
So far I have the following code which works fine as long as I select a text in the div but if I just position my cursor there without selecting anything it inserts my text outside the div.
How can I get it to add my text always at the cursor position the same way it does now at the selection position ? (I don't even need it to replace a selection as it would only be required at the cursor position. Also, this would only be required for one specific div.)
My Code:
<html>
<head>
<script type="text/javascript">
function test()
{
var input = "TEST";
document.selection.createRange().pasteHTML(input);
}
</script>
</head>
<body>
<div id="myDiv" contenteditable>This is a test text.</div><br />
<button type="button" onclick="test()">Test</button>
</body>
</html>
Thanks for any help with this, Tim
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…