How to get character position when click on text in javascript

前端 未结 2 1407
一个人的身影
一个人的身影 2020-12-16 22:27

I have this function to get position of the cursor when you click on the text, it only works for monospace characters which is fine, but it obviously don\'t work with charac

2条回答
  •  醉酒成梦
    2020-12-16 22:46

    Third attempt. Stuff a pipe character in there to pretend to be a cursor.

    https://developer.mozilla.org/en-US/docs/Web/API/Selection

    window.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.charPosition').forEach(el => {
        let clean, cursor;
        el.addEventListener('click', e => {
            let position = window.getSelection().focusOffset;
            if (cursor && position > cursor)
                position--;
            if (clean)
                el['innerText'] = clean;
            let textnode = el.firstChild['splitText'](position);
            clean = textnode.wholeText;
            cursor = position;
            el.insertBefore(document.createTextNode('|'), textnode);
            el['innerText'] = textnode.wholeText;
        });
    });
    });
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

提交回复
热议问题