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

扶醉桌前 提交于 2019-12-21 12:19:01

问题


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?


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3628299/is-it-possible-to-work-out-where-in-a-ps-text-a-mouse-click-event-occurred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!