我正在尝试开发一个所见即所得的编辑器。 在编辑器中,我试图在 onkeydown 函数触发时找到“br”的位置。
<p><b>1234</b><br><br>678</p>
当我将光标定位到 6 附近时,使用“oSelection.anchorNode.nodeValue”得到 678。 当我在“br”附近找到 cursot 时,什么也没得到。
我想查找光标附近的前后标记?
最佳答案
更新2:与ismail交谈后,问题可以改为:如何找出光标之前/之后的元素是否是<br>
标签。这可以这样实现:
var selection = window.getSelection(),
isBRBeforeCursor = IsBRBeforeCursor(selection),
isBRAfterCursor = IsBRAfterCursor(selection);
function GetPreviousSibling(node) {
if (node.previousSibling != null) {
return node.previousSibling;
} else if (node.parentNode != null) {
return GetPreviousSibling(node.parentNode);
} else {
return null;
}
}
function GetNextSibling(node) {
if (node.nextSibling != null) {
return node.nextSibling;
} else if (node.parentNode != null) {
return GetNextSibling(node.parentNode);
} else {
return null;
}
}
function IsBRBeforeCursor(selection) {
if(selection.anchorNode.nodeName === '#text') {
if(selection.anchorOffset > 0) {
// There is text before the cursor
return false;
} else {
var previousSibling = GetPreviousSibling(selection.anchorNode);
return previousSibling !== null && previousSibling.nodeName === 'BR';
}
} else {
if(selection.anchorOffset > 0) {
return selection.anchorNode.childNodes[selection.anchorOffset - 1].nodeName === 'BR';
} else {
var previousSibling = GetPreviousSibling(selection.anchorNode);
return previousSibling !== null && previousSibling.nodeName === 'BR';
}
}
}
function IsBRAfterCursor(selection) {
if(selection.anchorNode.nodeName === '#text') {
if(selection.anchorOffset < selection.anchorNode.nodeValue.length) {
// There is text after the cursor
return false;
} else {
var nextSibling = GetNextSibling(selection.anchorNode);
return nextSibling !== null && nextSibling.nodeName === 'BR';
}
} else {
if(selection.anchorNode.childNodes.length > selection.anchorOffset) {
return selection.anchorNode.childNodes[selection.anchorOffset].nodeName === 'BR';
} else {
var nextSibling = GetNextSibling(selection.anchorNode);
return nextSibling !== null && nextSibling.nodeName === 'BR';
}
}
}
<小时/>
更新:我认为始终找到正确的上一个/下一个元素有点棘手,因为文本本身就是一个节点。因此,要获取上一个/下一个元素,有时需要先上一级,然后再向左和向右查看。看一下下面的示例:
<p><b>123</b><br><u><i><br>456</i></u><br></p>
光标位于 1 和 2 之间。
下一个元素是
<br>
,它向上一层,然后向右。光标位于 4 和 5 之间。
前一个元素是
<br>
,它只是左边的一个。 下一个元素是<br>
,它向上两层,然后向右。
如果是这种情况,您可以像这样查找上一个/下一个元素:
function getElementBeforeSelection() {
var anchor = window.getSelection().anchorNode;
while(anchor.previousSibling === null && anchor.nodeName != 'BODY') {
anchor = anchor.parentNode;
}
return anchor.previousSibling;
}
<小时/>
原始答案:您可以使用 parentNode
、 previousSibling
和 nextSibling
获取周围的元素。所以光标前后的标签是:
var anchorNode = window.getSelection().anchorNode,
before = anchorNode.previousSibling,
after = anchorNode.nextSibling;
关于javascript - 使用 window.getSelection 在所见即所得编辑器中查找 <br> 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20246421/