Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

jquery - JavaScript: get cursor position in contenteditable div

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is that the <button> element steals the focus and destroys the selection by the time the click event has fired in IE. You could make the <button> unselectable, which would prevent it being able to receive focus. This is done using the unselectable attribute in IE:

<button type="button" unselectable="on" onclick="test()">Test</button>

Demo: http://jsbin.com/aqAYUwu/5

Another alternative which is less good in my view is to use the mousedown event instead and prevent the default action:

<button type="button" unselectable="on"
    onmousedown="test(); return false">Test</button>

You can find a cross-browser function to insert HTML at the current cursor position in a contenteditable element here:

https://stackoverflow.com/a/6691294/96100

One final note: contenteditable isn't a boolean attribute so strictly speaking you should give it a value (i.e. <div contenteditable="true">), although <div contenteditable> does work in all browsers I've tried it in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...