开发者

Is it possible to work out where in a p's text a mouse click event occurred?

开发者 https://www.devze.com 2023-01-14 10:18 出处:网络
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 c

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 cu开发者_运维百科rsor to that same point?


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 :)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消