style、 currentStyle、 runtimeStyle区别分析javascript技巧

Html代码 复制代码 收藏代码
  1. 1、obj.style只能获得内嵌样式(inline Style)就是写在Tag里面的,他访问不到那些链接的外部css和在head中用<style>声明的style。
  2. 所以必须认识到在那些使用外部Css文件的页面中,如果用style赋值,如obj.style=“color:red”;显然效果是正确的,其中的奥秘确是只是在该对象的tag上多添加了一个style属性,按照由小到大的优先级呈现罢了。
  3. 2、obj.currentStyle就强大多了,他能够获取关于这个节点所有位置的style,但是他也按照优先级,说穿了就是显示的是什么他就是指向哪一个style,如下代码字体优先是显示blue的,那currentStyle.color就是blue,当然此时style.color也会是blue。
  4. 复制代码 代码如下:
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  8. <title>testStyle</title>
  9. <style>
  10. .lala{
  11. color:yellow;
  12. }
  13. </style>
  14. </head>
  15. <body>
  16. <div id="tt" style="color:blue;" class="lala">1111</div>
  17. </body>
  18. <script>
  19. alert(document.getElementById("tt").currentStyle.color);
  20. </script>
  21. </html>
  22. 若去掉以上<div>中的style为<div id="tt" class="lala">1111</div>,那么currentStyle.color就根据优先级变成了yellow,但是此时style.color为空。
  23. 3、runtimeStyle简单的说就是你可以对一个节点的样式赋值,他将成为最高优先级的节点样式。
  24. 如:
  25. 复制代码 代码如下:
  26. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  27. <html>
  28. <head>
  29. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  30. <style>
  31. .lala{
  32. color:yellow;
  33. }</style>
  34. </head>
  35. <body>
  36. <div id="tt" style="color:blue;" class="lala">1111</div>
  37. </body>
  38. <script>
  39. document.getElementById("tt").runtimeStyle.color="black";
  40. alert(document.getElementById("tt").currentStyle.color);
  41. alert(document.getElementById("tt").runtimeStyle.color);
  42. alert(document.getElementById("tt").style.color);
  43. </script>
  44. </html>
  45. 此时页面显示字的颜色是runtimeStyle赋值后的black。但是只有currentStyle.color和runtimeStyle本身能够取到这个值,style.color取到的依然是tag中的blue。   
原文地址:https://www.cnblogs.com/bjanzhuo/p/3576100.html