2011-07-26 69 views
2

我需要与textContent等效的IE。对于IE的textContent(空白保留innerText)

在跳下裤子的位置之前 - innerText与textContent不一样。 innerText在DOM呈现器解析时解析空白区域。 textContent在写入时解析空白字符。我需要后者,但I.E.不支持textContent。

例如:

DOM Obj: <p>This is an example.</p> 
innerText: "This is an example." 
textContent: "This is an example." 

回答

1

我不认为你可以。即使在TextNode#nodeValue属性中,IE也“正常化”这些空间。前一阵子我写了这个:

function textValue(element) { 
    var collector = []; 
    textValueCollector(element, collector); 
    return collector.join(""); 
} 
function textValueCollector(element, collector) { 
    var node; 
    for (node = element.firstChild; node; node = node.nextSibling) 
    { 
     switch (node.nodeType) { 
      case 3: // text 
      case 4: // cdata 
       collector.push(node.nodeValue); 
       break; 
      case 8: // comment 
       break; 
      case 1: // element 
       if (node.tagName == 'SCRIPT') { 
        break; 
       } 
       // FALL THROUGH TO DEFAULT 
      default: 
       // Descend 
       textValueCollector(node, collector); 
       break; 
     } 
    } 
} 

所以我认为这可能是你需要的,但可悲的是,没有。正如您在this live example中看到的那样,在IE上,即使我们直接在文本节点上行走,额外的空间也不会被忽略,因此它只显示45的长度,在现实中为61(以及其他浏览器[Chrome,Firefox,Opera ])。