本文介绍了获取元素的innerText,但排除隐藏的子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从节点获取文本,使其像 innerText一样以空格格式返回文本,但不包括隐藏的后代节点(样式显示:无)?

How can I get text from a node so that it returns it with whitespace formatting like "innerText" does, but excludes descendant nodes that are hidden (style display:none)?

推荐答案

更新:正如OP在下面的注释中指出的,即使,在IE中表示情况并非如此。总结:

UPDATE: As the OP points out in comments below, even though MDN clearly states that IE introduced innerText to exclude hidden content, testing in IE indicates that is not the case. To summarize:


  • Chrome浏览器: innerText 仅从 visible 元素。

  • IE: innerText 返回所有文本,而不考虑元素的可见性。

  • Firefox: innerText 未定义(,以及在我的测试中。)

  • Chrome: innerText returns text only from visible elements.
  • IE: innerText returns all text, regardless of the element's visibility.
  • Firefox: innerText is undefined (as indicated by the W3C, and in my testing).

将所有这些加起来,您便拥有了避免像瘟疫一样。请继续阅读以获取解决方案。...

Add all of this up, and you have a property to avoid like the plague. Read on for the solution....

如果您希望跨浏览器兼容,则必须使用自己的函数。这是一个效果很好的方法:

If you want cross-browser compatibility, you'll have to roll your own function. Here's one that works well:

function getVisibleText( node ) {
    if( node.nodeType === Node.TEXT_NODE ) return node.textContent;
    var style = getComputedStyle( node );
    if( style && style.display === 'none' ) return '';
    var text = '';
    for( var i=0; i<node.childNodes.length; i++ ) 
        text += getVisibleText( node.childNodes[i] );
    return text;
}

如果您想变得痛苦聪明,您可以可以在 Node 对象上创建一个属性,这样感觉就更自然了。起初,我认为这是在Firefox上填充 innerText 属性的一种聪明方法,但是该属性并未作为 Node 对象原型,因此您确实会在那玩火。但是,您可以创建一个新属性,例如 textContentVisible

If you want to get painfully clever, you can create a property on the Node object so that this feels more "natural". At first I thought this would be a clever way to polyfill the innerText property on Firefox, but that property is not created as a property on the Node object prototype, so you would really be playing with fire there. However, you can create a new property, say textContentVisible:

Object.defineProperty( Node.prototype, 'textContentVisible', {
    get: function() { 
       return getVisibleText( this );
    }, 
    enumerable: true
});

这里是一个展示这些技术的JsFiddle:

Here's a JsFiddle demonstrating these techniques: http://jsfiddle.net/8S82d/

这篇关于获取元素的innerText,但排除隐藏的子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:08