我有这个 html: <span>some words here</span>
。单击它时,span
它会变成一个带有该字符串的文本框。一旦出现带有字符串的文本框,有没有办法找出单击发生的字符并将光标放在字符串中的该点?
问问题
1204 次
1 回答
2
这是一个快速的 Fiddle(在 Chrome 中测试),适用于<span>
包含换行符的 a,上述解决方案阻塞了它:
总结如下:
function swapArea(baseEl) {
// Display <textarea> element, hide the <span>
}
function getCursorLoc (nodes, range) {
var prevChars = 0;
var clickContent = range.startContainer.textContent;
var clickLine;
//iterate backwards through nodes constituting <span> element contents
for (x = nodes.length - 1; x >= 0; x--) {
node = nodes[x];
if (clickContent == node.textContent) {
clickLine = node; //this is the line user clicked in
}
else if (clickLine && (node.nodeName == "#text") ) {
//sum up length of text lines prior, +1 for the NewLine
prevChars += node.textContent.length + 1;
}
}
//return offset in line clicked + sum length of all previous lines' content
return range.startOffset + prevChars;
}
function replaceAndSet(e) {
//Capture the click target as Selection(), convert to Range();
var userRange = window.getSelection().getRangeAt();
newArea = swapArea(source);
//spanLines holds siblings (nodeName #Text or <BR>) constituting <span> contents
var spanLines = userRange.startContainer.parentElement.childNodes;
var clickChar = getCursorLoc(spanLines, userRange);
newArea.focus();
newArea.setSelectionRange(clickChar, clickChar);
}
var source = someSpan; //the span user clicks on
source.onclick = replaceAndSet;
于 2012-06-07T00:41:07.483 回答