问题
I want to know what is the parent element of caret in an iframe
with designMode = 'on'
.
The reason is that want to know if currently user is typing in a p
tag.
回答1:
Here's a function to do this, adapted from an answer to a similar question:
function getSelectionBoundaryElement(win, isStart) {
var range, sel, container = null;
var doc = win.document;
if (doc.selection) {
// IE branch
range = doc.selection.createRange();
range.collapse(isStart);
return range.parentElement();
} else if (win.getSelection) {
// Other browsers
sel = win.getSelection();
if (sel.rangeCount > 0) {
range = sel.getRangeAt(0);
container = range[isStart ? "startContainer" : "endContainer"];
// Check if the container is a text node and return its parent if so
if (container.nodeType === 3) {
container = container.parentNode;
}
}
}
return container;
}
Example use:
var iframe = document.getElementById("your_iframe_id");
var caretElement = getSelectionBoundaryElement(iframe.contentWindow, true);
来源:https://stackoverflow.com/questions/14546568/get-parent-element-of-caret-in-iframe-design-mode