gpt4 book ai didi

Javascript:向页面中具有特定计算样式属性的元素添加内联样式

转载 作者:行者123 更新时间:2023-11-28 02:07:10 27 4
gpt4 key购买 nike

我正在尝试向页面中具有特定计算样式属性的元素添加内联样式。

例如:

<head>
<style>
p.mim {
cursor:pointer;
}

a.fif {
cursor:pointer;
}

</style>
</head>
<body>
<p class="mim">prova</p>
<a class="fif">prova</a>
</body>

我想为每个在计算样式中设置了“cursor:pointer”的元素添加一个内联样式“cursor:wait”:

<body>
<p class="mim" style="cursor:wait;">prova</p>
<a class="fif" style="cursor:wait;">prova</a>
</body>

这是我尝试过的:

var elms = document.getElementsByTagName("*");
for (var j = 0; j < elms.length; j++) {

var crs = getComputedStyle(elm, null).getPropertyCSSValue('cursor') || "";
crs = crs.replace(/\s/g, "").toLowerCase();

switch (crs) {
case "pointer":
case "Pointer":
case "POINTER":
elm.style.cursor = "wait";
break;
}
});

最佳答案

由于多种原因,您的代码是多余的,而对于其他原因则不完整。

首先,getComptedStyle 在早期版本的 IE 中不存在。他们改为使用 currentStyle 属性。值得庆幸的是,要对此进行填充非常容易:

if( typeof getComputedStyle == "undefined") getComputedStyle = function(elem) {return elem.currentStyle;};

既然已经解决了,请删除那个 null 参数,因为它是完全多余的。实际上,我什至不知道 getComputedStyle 第二个参数,但那只是我。

接下来,您可以通过获取 .cursor(或 ['cursor'])而不是 .getPropertyCSSValue 来获取光标属性打电话(我又一次从未听说过......)。您还可以删除 || "" 因为 getComputedStyle 如果未设置 cursor 属性将返回一个空字符串。

您不需要 trim 空格,但为了安全起见,切换为小写似乎是个好主意。

...但是,紧接在 toLowerCase() 之后,您检查了单词的三种不同的大写形式?真的吗?

此外,您永远不会定义 elm(这是您的实际问题所在),您应该缓存 elms.length 的值。

最终代码应该是这样的:

if( typeof getComputedStyle == "undefined") getComputedStyle = function(elem) {return elem.currentStyle;};
var elms = document.getElementsByTagName("*"), l = elms.length, i;
for( i=0; i<l; i++) {
if( getComputedStyle(elms[i]).cursor.toLowerCase() === "pointer") {
elms[i].style.cursor = "wait";
}
}

如果您希望能够撤消此操作,您将需要存储一个您正在修改的元素数组,遍历它并删除样式 (.style.cursor = "";).

关于Javascript:向页面中具有特定计算样式属性的元素添加内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10769498/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com