【问题标题】:Why is TextRange.parentElement returning the parent of the FINAL element in my range?为什么 TextRange.parentElement 返回我范围内 FINAL 元素的父级?
【发布时间】:2012-07-30 18:09:10
【问题描述】:

这是我的 HTML:

<ul contenteditable>
  <li>Hi there 1</li>
  <li>HI 2 2 2 2 2</li>
  <ul><li>hi 3</li></ul> <!-- I know it's invalid, it's what document.execCommand('indent') yields -->
  <li> hi 4 hi there people 4 here now </li>
</ul>

(下周可以在http://www.webdevout.net/test?06&raw查看)

我正在尝试确定当前选择的文本(在 IE8 中)是在一个 LI 内还是跨越多个 LI。当我选择了 LI 的一和二的全部,然后在控制台document.selection.createRange().parentElement().innerHTML 中输入以下内容,只返回第二个 LI (HI 2 2 2 2 2 2) 的内容。 p>

为什么 TextRange.parentElement 返回范围内的最后一个元素而不是整个范围的父级?

The docs 说“如果文本范围跨越多个元素中的文本,则此方法返回包含所有元素的最小元素。”我的最终目标是确定是否选择了多个 LI;我认为“检查 parentElement().nodeName.toUppercase === "LI"" 是否会这样做,但如果 parentElement() 没有返回 parentElement,我就不能这样做。

【问题讨论】:

标签: internet-explorer internet-explorer-8 contenteditable textrange


【解决方案1】:

我以前见过这种东西,它是 IE 中的一个错误。我在Rangy 库中使用的解决方法是使用三个元素的最内层共同祖先:

  • TextRange 的parentElement()
  • 调用collapse(true)后TextRange的parentElement()
  • 调用collapse(false)后TextRange的parentElement()

这是 Rangy 的代码:

/*
 This is a workaround for a bug where IE returns the wrong container
 element from the TextRange's parentElement() method. For example,
 in the following (where pipes denote the selection boundaries):

 <ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul>

 var range = document.selection.createRange();
 alert(range.parentElement().id); // Should alert "ul" but alerts "b"

 This method returns the common ancestor node of the following:
 - the parentElement() of the textRange
 - the parentElement() of the textRange after calling collapse(true)
 - the parentElement() of the textRange after calling collapse(false)
 */
var getTextRangeContainerElement = function(textRange) {
    var parentEl = textRange.parentElement();

    var range = textRange.duplicate();
    range.collapse(true);
    var startEl = range.parentElement();

    range = textRange.duplicate();
    range.collapse(false);
    var endEl = range.parentElement();

    var startEndContainer = (startEl == endEl) ?
        startEl : dom.getCommonAncestor(startEl, endEl);

    return startEndContainer == parentEl ?
        startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer);
};

【讨论】:

    猜你喜欢
    • 2019-11-03
    • 1970-01-01
    • 2013-01-31
    • 2011-11-16
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多