How to get text cursor position using javascript

this is my code, i fill the space with everything in a div, (use jquery):

<div id="a" style="position:absolute;top:300px;width:100px;height:100px;background:red;color:black;word-wrap:break-word;">
    <div id='a2' contenteditable=true ></div>
</div>
<script type="text/javascript">
    String.prototype.repeat = function(n) {
        return new Array(1 + parseInt(n, 10)).join(this);
    }

    var s=$('#a').width()/4*$('#a').height()/19;
    $('#a2').html('&nbsp;'.repeat($('#a').width()/4*parseInt($('#a').height()/19)))

    $('#a2').click(function(){
        alert('sss')
    })

</script>

so how can i get the position of the text cursor when i click somewhere in the 'a2' div

demo http://jsfiddle.net/KBnKc/

thank

+3
source share
2 answers

You can use the pageX and pageY property of the jQuery event object:

$('#a2').click(function(e) {
    alert(e.pageX + ", " + e.pageY);
});

The returned coordinates refer to the upper left corner of the document.

, A-Tools, getSelection(). , .

, " " :)

EDIT: contenteditable <div>. , . , .

+2

Prototype.js, :

var x, y;
function getCoordinatesInsideElement(e)
{
    x = Event.pointerX(e);
    y = Event.pointerY(e);
    /* DO-SOMETHING */
}

. : http://api.prototypejs.org/

0

Source: https://habr.com/ru/post/1777120/


All Articles