我正在尝试通过Javascript更改页面中所有链接的样式。
我试过这两个但没有成功:
document.links.style.cursor = "wait";
document.getElementsByTagName(a).style.cursor = "wait";
我做错了什么?
答案 0 :(得分:5)
var allLinks = document.links || document.getElementsByTagName('a');
for(var n=0;n<allLinks ;n++)
document.allLinks [n].style.cursor = "wait";
document.links
是一个元素数组,因此document.links.style.cursor = "wait"
等于[link1,link2].links.style.cursor = "wait"
。
关于document.getElementsByTagName(a)
:语法错误,你忘记了引号。正确的是document.getElementsByTagName("a")
答案 1 :(得分:1)
var style = document.createElement("style");
document.head.appendChild(style);
try {
style.innerHTML = "a { cursor: wait; }";
}
catch (_ie) {
style.styleSheet.cssText = "a { cursor: wait; }";
}
当然,您也可以提前计划需要更改链接的可能性,并预加载这样的静态样式表:
.wait-links a { cursor: wait; }
然后,每当您将“等待链接”类添加到<body>
(或您喜欢的任何容器)时,<a>
标记都会受到影响。这比迭代改变他们的个人风格(可能)的元素要有效得多,但如果没有很多链接,那可能无关紧要。
在我看来,使用样式表是一种更好的做法。事实上,在这种情况下,最好不要将类称为“等待链接”,而是使用一些描述实际情况的单词或单词。然后,您的JavaScript代码只是通过添加(或删除)类来建立情境,样式表控制外观更改。如果你认为在某些情况下这种情况要求链接改变颜色或变得不可见,你可以这样做,而不必在你的脚本中查找样式更改。
答案 2 :(得分:0)
使用JQuery和“ .css”方法无需使用for循环并简化了代码。
$('a').css("cursor","wait");