2011-10-14 26 views

回答

4

也许动态地为此创建一个css。

var styleElement = document.createElement("style"); 
styleElement.type = "text/css"; 
if (styleElement.styleSheet) { 
    styleElement.styleSheet.cssText = "a { color: red }"; 
} else { 
    styleElement.appendChild(document.createTextNode("a { color: red; }")); 
} 
document.getElementsByTagName("head")[0].appendChild(styleElement); 
+0

+1,不铃铛答案非常感谢! – 2011-10-14 06:24:08

2

document.anchors返回一个数组,你应该循环它们。

var anchors = document.anchors; 
for(var i=0, m=anchors.length; i<m; i++){ 
    anchors[i].style.color = "red"; 
} 
0

已经回答了,不过我很好反正版本:)

<html> 
    <head> 
     <script type="text/javascript"> 
     var ChangeColors = function() { 
      var elem = document.createElement('style'); 
      elem.setAttribute("type", "text/css"); 
      var style = document.createTextNode("A, A:hover, A:visited { color: red; }") 
      elem.appendChild(style); 
      document.getElementsByTagName("head")[0].appendChild(elem); 
     } 
     </script> 
    </head> 
    <body> 
     <a href="#">Some Link</a><br /> 
     <a href="http://www.google.com">Some Other Link</a><br /> 
     <input type="button" onclick="ChangeColors();"/> 
     <a href="#">Some Link 2</a><br /> 
     <a href="#">Some Link 3</a><br /> 
    </body> 
</html> 
+0

向下投票人:如果你能解释为什么你投下了这个帖子,那将是非常感谢。谢谢。 – Vinzenz