Is it possible to work out where in a p's text a mouse click event occurred?
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?
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.
链接地址: http://www.djcxy.com/p/47572.html上一篇: 用POCO和t4模板测试EF 4.0