我正在使用document.getSelection()
來選擇一些文本。我想知道所選範圍包含的元素類型(我特別想知道它是否是錨標籤)。獲取包含在範圍內的HTML元素
var selection = document.getSelection();
var range = selection.getRangeAt(0);
所以我可以得到範圍,但我怎麼知道該範圍內的元素?很高興使用普通的js或jQuery。
編輯:
這裏是我想出了:
var updateLink = function(url) {
var selection = document.getSelection();
var range = selection.getRangeAt(0);
if (range != 0) {
var containerElement = range.commonAncestorContainer;
if (containerElement.nodeType != 1) {
containerElement = containerElement.parentNode;
var e = $(containerElement);
e.attr('href', url);
}
}
}//end
讀:https://developer.mozilla.org/en-US/docs/Web/API/Selection?redirectlocale=en-US&redirectslug=DOM%2FSelection – diEcho
嘗試使用[瘦長] (https://code.google.com/p/rangy/),它使得選擇更容易。 –