如果在HTML文档中有两个节点,如何使用DOM方法判断Javascript中HTML文档顺序中的哪个节点最先出现?

例如,

function funstuff(a, b) {
    //a and b can be any node in the DOM (text, element, etc)
    if(b comes before a in document order) {
        var t = b; b = a; a = t;
    }
    // process the nodes between a and b. I can handle this part
    // when I know that a comes before b.
}

最佳答案

Resig to the rescue:

// Compare Position - MIT Licensed, John Resig
function comparePosition(a, b){
  return a.compareDocumentPosition ?
    a.compareDocumentPosition(b) :
    a.contains ?
      (a != b && a.contains(b) && 16) +
        (a != b && b.contains(a) && 8) +
        (a.sourceIndex >= 0 && b.sourceIndex >= 0 ?
          (a.sourceIndex < b.sourceIndex && 4) +
            (a.sourceIndex > b.sourceIndex && 2) :
          1) +
      0 :
      0;
}

09-28 07:56