outerText和innerText属性的区别实例介绍
分类:实例代码
在开始文章技术细节的区别介绍之前,先来阐明一个标准上的区别:
outerText是符合W3C标准的,而innerText则是非标准的。
下面来先来看一段代码实例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <script type="text/javascript"> window.onload=function(){ var top=document.getElementById("top"); var bottom=document.getElementById("bottom"); var str=""; str=str+top.outerText; str=str+"\n"; str=str+bottom.innerText; alert(str); } </script> </head> <body> <div id="top">前端教程网</div> <div id="bottom">前端教程网</div> </body> </html>
从上面的代码来看,使用outerText和innerText属性获取的值都是一样的,没错,这两个属性在获取值的功能上是完全一样的,但是在设置内容的功能上有差别,代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <style> div{ color:red; } </style> <script type="text/javascript"> window.onload=function(){ var top=document.getElementById("top"); var bottom=document.getElementById("bottom"); top.outerText="<b>前端教程网</b>"; top.innerText="<b>前端教程网</b>"; } </script> </head> <body> <div id="top">前端教程网</div> <div id="bottom">前端教程网</div> </body> </html>
在上面的代码可以明显看出两个属性在设置属性值上是有明显的差异的。
outerText属性可以将原来元素节点被文本节点替换掉,而innerText不会,看如下截图: