업데이트 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';
}
}
}
업데이트 : 나는 텍스트가 노드 자체이기 때문에 항상 정확한 이전/다음 요소를 찾기 위해 조금 까다 롭습니다 생각. 따라서 이전/다음 요소를 얻으려면 왼쪽과 오른쪽을보기 전에 레벨을 올려야합니다. 다음 요소는 오른쪽에 다음 한 수준 위로 인 <br>
입니다
1 ~ 2
<p><b>123</b><br><u><i><br>456</i></u><br></p>
커서는 다음 예제를 보라. 이전 요소 바로 왼쪽에 하나 인 <br>
이다
4 내지 5
커서이다. 다음 요소는 <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;
출처
2013-11-27 16:53:18
Jan
456
커서 후 4 previousSibling은로 nextSibling은'456'은''노드의 자식 인 텍스트 노드이기 때문입니다 그 –
널 : 그래서 이전과 커서 후 태그는 . 따라서 '
'을 얻으려면 먼저 한 레벨 위로 이동해야합니다 :'window.getSelection(). parentNode.nextSibling'. – Jan
더 복잡한 태그 예 : 최대 몇 개입니까? –