How to get character position when click on text in javascript

前端 未结 2 1405
一个人的身影
一个人的身影 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:33

    window.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('.charPosition').forEach(el => {
            let characters = el['innerText'].split('');
            el.innerHTML = '';
            characters.forEach(char => {
                let span = document.createElement('span');
                span.innerText = char;
                span.addEventListener('click', function () {
                    let position = 0;
                    let el = this;
                    while (el.previousSibling !== null) {
                        position++;
                        el = el.previousSibling;
                    }
                    console.log(this.innerHTML + ':' + position);
                });
                el.appendChild(span);
            });
        });
    });
    <div class="charPosition">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>

    0 讨论(0)
  • 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;
        });
    });
    });
    <div class="charPosition">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>

    0 讨论(0)
提交回复
热议问题