我如何从一个节点获取文本,以便它像“innerText”一样以空白格式返回它,但不包括隐藏的后代节点(样式显示:无)?
最佳答案
更新:正如 OP 在下面的评论中指出的那样,即使 MDN clearly states that IE introduced innerText
to exclude hidden content ,在 IE 中测试表明并非如此。总结:
- Chrome:
innerText
仅从可见 元素返回文本。 - IE:
innerText
返回所有文本,无论元素的可见性如何。 - Firefox:
innerText
未定义(as indicated by the W3C,在我的测试中)。
将所有这些加起来,您就有了一个像瘟疫一样需要避免的属性(property)。继续阅读解决方案....
如果你想要跨浏览器兼容性,你将不得不推出你自己的功能。这是一个效果很好的:
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
对象原型(prototype)上的属性创建的,因此您会那里真的是在玩火。但是,您可以创建一个新属性,比如 textContentVisible
:
Object.defineProperty( Node.prototype, 'textContentVisible', {
get: function() {
return getVisibleText( this );
},
enumerable: true
});
这是一个演示这些技术的 JsFiddle:http://jsfiddle.net/8S82d/
关于javascript - 获取元素的 innerText,但排除隐藏的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19985306/