Jak Mogę uzyskać element DOM, który zawiera bieżący wybór?
Możesz wybrać część strony internetowej za pomocą myszki.
Wiem, że mogę pobrać aktualnie zaznaczony tekst ale jak mogę pobrać element DOM, który zawiera początek lub koniec bieżącego zaznaczenia?
32
Author: Aaron Digulla, 2009-08-26
2 answers
W IE użyj dokumentu.wybór.createRange ().parentElement () i w rzeczywistych przeglądarkach używa window.getSelection ().getRangeAt(0)startContainer.parentNode. Coś takiego:
function getSelectedNode()
{
if (document.selection)
return document.selection.createRange().parentElement();
else
{
var selection = window.getSelection();
if (selection.rangeCount > 0)
return selection.getRangeAt(0).startContainer.parentNode;
}
}
26
Author: InvisibleBacon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-26 14:57:19
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-26 14:57:19
Poniżej zostanie zwrócony element elementu początkowego lub końcowego bieżącego zaznaczenia, używając elementu logicznegoisStart
, aby określić, czy chcesz mieć granicę początkową czy końcową. Będzie działać w większości popularnych przeglądarek. Dodaj testy funkcji, aby uzyskać większą wytrzymałość.
function getSelectionBoundaryElement(isStart) {
var range, sel, container;
if (document.selection) {
range = document.selection.createRange();
range.collapse(isStart);
return range.parentElement();
} else {
sel = window.getSelection();
if (sel.getRangeAt) {
if (sel.rangeCount > 0) {
range = sel.getRangeAt(0);
}
} else {
// Old WebKit
range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
// Handle the case when the selection was selected backwards (from the end to the start in the document)
if (range.collapsed !== sel.isCollapsed) {
range.setStart(sel.focusNode, sel.focusOffset);
range.setEnd(sel.anchorNode, sel.anchorOffset);
}
}
if (range) {
container = range[isStart ? "startContainer" : "endContainer"];
// Check if the container is a text node and return its parent if so
return container.nodeType === 3 ? container.parentNode : container;
}
}
}
54
Author: Tim Down,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-17 10:17:07
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-17 10:17:07