Is it possible to work out where in a p's text

2020-07-10 08:17发布

I have a <p> containing text. When the <p> is clicked on, I create a <textarea> containing the text from the <p>. Is it possible to calculate where in the <p>'s text the click occurred, and move the <textarea>'s cursor to that same point?

3条回答
唯我独甜
2楼-- · 2020-07-10 08:58

I don't believe so, no. The DOM just knows what containing element received the click event, it doesn't distinguish between pieces of text within the containing element unless they are elements themselves. And I doubt you want to wrap every character in your text with its own element tag :)

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-07-10 09:01

I'm guessing this is going to take a fair amount of fiddling to get right, and you won't be able to get it exactly right. But you'll probably want to use event.clientX and event.clientY.

EDIT -- didn't know about this stuff when I replied. Looks pretty possible to get it exactly correct. http://www.quirksmode.org/dom/range_intro.html

An alterntive idea: style the textarea so it looks like plain text, and re-style it to look like a form field when it gets clicked.

查看更多
▲ chillily
4楼-- · 2020-07-10 09:12

Hope this simple example helps:

<html>
<head/>

<body>
<script type='text/javascript'>

function getPosition() 
{   
        var currentRange=window.getSelection().getRangeAt(0);   
        return currentRange.endOffset;
}

function setPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

function test()
{
    setPosition('testId', getPosition());
}


</script>
<p onclick = 'test()'>1234567890</p>
<textarea  id='testId'>123467890</textarea>
</body>
</html>

Or you can use third-party JS library like jQuery - see this example.

查看更多
登录 后发表回答