简体   繁体   English

Javascript:如何更改页面中所有链接的样式?

[英]Javascript: how to change the style of all links in a page?

I'm trying to change the style of all links in a page via Javascript. 我正在尝试通过Javascript更改页面中所有链接的样式。

I tried both these but no success: 我尝试了这两种方法,但均未成功:

document.links.style.cursor = "wait";
document.getElementsByTagName(a).style.cursor = "wait";

What am I doing wrong? 我究竟做错了什么?

var allLinks = document.links || document.getElementsByTagName('a');
for(var n=0;n<allLinks ;n++)
    document.allLinks [n].style.cursor = "wait";

The document.links is an array of elements, so document.links.style.cursor = "wait" equals to [link1,link2].links.style.cursor = "wait" . document.links是元素数组,因此document.links.style.cursor = "wait"等于[link1,link2].links.style.cursor = "wait"
And about document.getElementsByTagName(a) : the syntax is wrong, you forgot the quotes. 关于document.getElementsByTagName(a) :语法错误,您忘记了引号。 The correct is document.getElementsByTagName("a") 正确的是document.getElementsByTagName("a")

var style = document.createElement("style");
document.head.appendChild(style);
try {
  style.innerHTML = "a { cursor: wait; }";
}
catch (_ie) {
  style.styleSheet.cssText = "a { cursor: wait; }";
}

Of course alternatively you could plan in advance for the eventuality of needing your links to change, and pre-load a static style sheet like this: 当然,您也可以预先计划需要更改链接的可能性,并预先加载静态样式表,如下所示:

.wait-links a { cursor: wait; }

Then whenever you add the class "wait-links" to the <body> (or any container you like), the <a> tags will all be affected. 然后,每当您将类“ wait-links”添加到<body> (或您喜欢的任何容器)时, <a>标记都将受到影响。 That'd be much more efficient than iterating over the elements changing their individual styles (probably), though if there aren't many links it probably doesn't matter. 这比遍历元素更改其个人样式的效率要高得多(可能),尽管如果链接不多,则可能无关紧要。

Using a style sheet for such things is, in my opinion, a much better practice. 在我看来,将样式表用于此类事情是一种更好的做法。 In this case, in fact, it'd be better not to call the class "wait-links", but rather use some word or words that describe what's actually happening. 实际上,在这种情况下,最好不要将类称为“ wait-links”,而应使用描述实际情况的一个或多个单词。 Then your JavaScript code just establishes the situation by adding (or removing) the class, and the style sheet controls the appearance changes. 然后,您的JavaScript代码只需通过添加(或删除)类来建立情况,然后样式表控制外观的更改。 If you decide that in some cases the situation calls for the links to change color or become invisible, you can do that without having to root around in your scripts looking for style changes. 如果您决定在某些情况下需要链接更改颜色或变得不可见,则可以这样做,而不必在脚本中扎根寻找样式更改。

使用JQuery和“ .css”方法无需使用for循环,从而简化了代码。

$('a').css("cursor","wait");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM