Is there a way I can change all links on my page to a certain color at the same time? such as:
document.anchors.style.color = "red";
probably with an o开发者_如何学编程nclick function i'm thinking. No luck so far.
Maybe dynamically create a css for that.
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);
document.anchors return an array, you should loop through them.
var anchors = document.anchors;
for(var i=0, m=anchors.length; i<m; i++){
anchors[i].style.color = "red";
}
It has been answered already but well my version anyway :)
<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>
精彩评论