我有一些JavaScript代码,在IE中包含以下内容:

myElement.innerText = "foo";

然而,'innerText'属性似乎在Firefox中不起作用。Firefox中有类似的吗?或者是否可以使用更通用的跨浏览器属性?


当前回答

从2016年的Firefox v45开始,innerText在Firefox上工作,看看它的支持:http://caniuse.com/#search=innerText

如果希望它能在以前版本的Firefox上运行,可以使用textContent,它在Firefox上有更好的支持,但在较旧的IE版本上更差:http://caniuse.com/#search=textContent

其他回答

如果您只需要设置文本内容而不需要检索,这里有一个简单的DOM版本,您可以在任何浏览器上使用;它既不需要IE的innerText扩展,也不需要DOM Level 3 Core textContent属性。

function setTextContent(element, text) {
    while (element.firstChild!==null)
        element.removeChild(element.firstChild); // remove all existing content
    element.appendChild(document.createTextNode(text));
}
myElement.innerText = myElement.textContent = "foo";

编辑(感谢Mark Amery在下面的评论):只有当您确信没有代码会像jQuery那样依赖于检查这些属性是否存在时,才会这样做。但如果你正在使用jQuery,你可能只需要使用"text"函数并执行$('#myElement').text('foo'),就像其他答案显示的那样。

注意,在谷歌Chrome中,Element::innerText属性将不包含被CSS样式“display:none”隐藏的文本(以及它将删除被其他CSS技术掩盖的内容(包括font-size:0, color:transparent,以及其他一些导致文本不以任何可见方式呈现的类似效果)。

其他CSS属性也被考虑:

First the "display:" style of inner elements is parsed to determine if it delimits a block content (such as "display:block" which is the default of HTML block elements in the browser's builtin stylesheet, and whose behavior as not been overriden by your own CSS style); if so a newline will be inserted in the value of the innerText property. This won't happen with the textContent property. The CSS properties that generate inline contents will also be considered : for example the inline element <br \> that generates an inline newline will also generate an newline in the value of innerText. The "display:inline" style causes no newline either in textContent or innerText. The "display:table" style generates newlines around the table and between table rows, but"display:table-cell" will generate a tabulation character. The "position:absolute" property (used with display:block or display:inline, it does not matter) will also cause a line break to be inserted. Some browsers will also include a single space separation between spans

但是Element::textContent仍然包含独立于应用CSS的内部文本元素的所有内容,即使它们是不可见的。textContent中不会生成额外的换行符或空格,它只是忽略了内部元素的所有样式和结构以及内联/块或定位类型。

使用鼠标选择的复制/粘贴操作将丢弃放在剪贴板中的纯文本格式的隐藏文本,因此它不会包含textContent中的所有内容,而只包含innerText中的内容(如上所述,在空格/换行生成之后)。

这两个属性然后在谷歌Chrome支持,但他们的内容可能会有所不同。旧的浏览器仍然包含在innetext的一切,就像textContent现在所包含的(但他们的行为与当时产生的空白/换行符是不一致的)。

jQuery将通过将".text()"方法添加到它通过$()查询返回的已解析元素中来解决浏览器之间的这些不一致。在内部,它通过查看HTML DOM来解决困难,只处理“节点”级别。它会返回一些看起来更像标准textContent的东西。

需要注意的是,这个jQuery方法不会插入任何额外的空格或换行符,这些空格或换行符可能是由内容的子元素(如<br />)引起的,在屏幕上可见。

如果您设计了一些可访问性脚本,并且您的样式表解析为非听觉呈现,例如用于与盲文阅读器通信的插件,如果它必须包括特定的标点符号,这些标点符号被添加到具有“display:none”样式的span中,并且通常包含在页面中(例如上标/下标),则该工具应该使用textContent,否则在盲文阅读器上innerText将非常混乱。

Texts hidden by CSS tricks are now typically ignored by major search engines (that will also parse the CSS of your HTML pages, and will also ignore texts that are not in contrasting colors on the background) using an HTML/CSS parser and the DOM property "innerText" exactly like in modern visual browsers (at least this invisible content will not be indexed so hidden text cannot be used as a trick to force the inclusion of some keywords in the page to check its content) ; but this hidden text will be stil displayed in the result page (if the page was still qualified from the index to be included in results), using the "textContent" property instead of the full HTML to strip the extra styles and scripts.

IF you assign some plain-text in any one of these two properties, this will overwrite the inner markup and styles applied to it (only the assigned element will keep its type, attributes and styles), so both properties will then contain the same content. However, some browsers will now no longer honor the write to innerText, and will only let you overwrite the textContent property (you cannot insert HTML markup when writing to these properties, as HTML special characters will be properly encoded using numeric character references to appear literally, if you then read the innerHTML property after the assignment of innerText or textContent.

也可以在其他浏览器中模拟innerText行为:

 if (((typeof window.HTMLElement) !== "undefined") && ((typeof HTMLElement.prototype.__defineGetter__) !== "undefined")) {
     HTMLElement.prototype.__defineGetter__("innerText", function () {
         if (this.textContent) {
             return this.textContent;
         } else {
             var r = this.ownerDocument.createRange();
             r.selectNodeContents(this);
             return r.toString();
         }
     });
     HTMLElement.prototype.__defineSetter__("innerText", function (str) {
         if (this.textContent) {
             this.textContent = str;
         } else {
             this.innerHTML = str.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/\n/g, "<br />\n");
         }
     });
 }

一个非常简单的Javascript行可以在所有主要浏览器中获得“非标记”文本……

var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);