获取 HTML 元素的行号

Get an HTML element's line number

想知道是否有更好的方法在源代码中查找元素行号。

这是我到目前为止所做的:

// Get the item that the user is clicking on:
var focused = doc.getSelection().anchorNode;
if(focused.nodeType == 3){ // text node
    focused = focused.parentNode;
}

// Get the entire page as a string
// NOTE: <!doctype> is not included in this!
var pageStr = doc.documentElement.outerHTML;

// Get the focused node's parent and 
// find where it begins in the page.
var parentNodeStr   = focused.outerHTML;
var parentNodeIndex = pageStr.indexOf(parentNodeStr);

// Find where the focused node begins in it's parent.
var focusedStr      = focused.outerHTML;
var focusedIndex    = parentNodeStr.indexOf(focusedStr);

// Now find where the focused node begins in the overall page.
var actualIndex     = parentNodeIndex - focusedIndex;

// Grab the text above the focused node
// and count the number of lines.
var contentAbove    = pageStr.substr(0, actualIndex);
var lineNumbers     = contentAbove.split("\n").length;

console.log("lineCount", lineNumbers);

这是我想出的一个更好的解决方案,希望这能帮助那些正在使用 Ace 或 CodeMirror 与 contenteditable 结合使用的人:

设置(新手)

我们可以使用以下方法获取用户 selecting 的位置:

var sel = document.getSelection();

selection 的开头称为 "anchor" 结尾叫做"focus"。例如, 当你 select 几句文字时,有 select离子的开始和结束。

var anchorPoint = elementPointInCode(sel.anchorNode, sel.anchorOffset);
var focusPoint = elementPointInCode(sel.focusNode, sel.focusOffset);

由于 HTML 包含标签和可读文本,因此有一个 抵消。例如:

<p>abcdefgh</p>
// ...^

偏移量是文本节点字符串中的索引。 在我们的示例中,字母 "d" 偏移了 4 个字符 从 >p< 标签的入口点。 但是偏移量是从零开始的,所以偏移量实际上是 3.

我们使用以下方法获得偏移量:

var offset = sel.anchorOffset;
// -- or --
var offset = sel.focusOffset;

...取决于我们想要什么,结束的开始。

函数

function elementPointInCode(element, offset) {

    // There may or may not be an offset.
    offset =  offset || 0;

    var node = element;

    // Process first node because it'll more-than-likely be a text node.
    // And we don't want to go matching text against any of the node HTML.
    //  e.g. <a href="page.html">page 1</a>
    //      where the text "page" sould match the "page" within the <a> attributes.

    var strIndex;
    var str;

    // Bump text nodes up to parent
    if(node.nodeType == 3) {
        node = node.parentNode;
        str = node.outerHTML;
        strIndex = str.indexOf(">") + offset + 1;
    } else {
        strIndex = ;
    }

    // This will ultimately contain the HTML string of the root node.
    var parentNodeStr = "";
    while(node){

        // Get the current node's HTML.
        var str = node.outerHTML;

        // Preemptively snag the parent
        var parent = node.parentNode;

        if(parent && str){

            // The <html> root, we won't have a parent.
            var outer = parent.outerHTML;

            if(outer){

                // Stash the node's HTML for post processing.
                parentNodeStr = outer;

                // Cumulatively count the offset's within each node
                strIndex += parentNodeStr.indexOf( str );

            }

        }

        // Work our way up to the root
        node = parent;

    }

    // Chop the root HTML by our cumulative string index
    var str = parentNodeStr.substr(0, strIndex);

    var Astr = str.split("\n" );

    return {
        row : Astr.length,
        col : Astr.pop().length
    }

};