Javascript:获取样式定义不正确的元素的内容

Javascript: get content of an element with incorrect style definition

本文关键字:元素 不正确 定义 获取 样式 Javascript      更新时间:2023-09-26

我正在为某个站点创建一个样式表,使用javascript为某些元素分配类。无论出于何种原因,一些"td"元素使用奇怪的类赋值和内联样式,所以我循环它们,清理它们并分配正确的类名以在外部样式表中引用。

我无权

访问网站本身(也无权更改任何内容),所以我使用 Stylish 和 Greasemonkey for Firefox(加上 Adblock 来处理原始样式表)。

这是负责此操作的js代码的一小部分:

var cellStyleBg = cCell.style.backgroundColor;
if (cellStyleBg) {
switch(cellStyleBg) {
    case 'white':
        cCell.removeAttribute('style');
         if ( cCell.parentNode.nodeName == 'TR' ) {
             cCell.parentNode.className = 'deadlineSet';
         }
         break;
...

问题是有一种特殊情况不起作用:

<td class="td2h" style="background: dd97f0;">

如您所见,颜色代码前面没有八角形。我认为这就是在这种情况下变量cellStyleBg为"null"的原因。

我尝试(而不是'cCell.style.backgroundColor')使用'cCell.style'和'cCell.style.background',但它们没有返回纯文本供我解析。

我该怎么做才能处理这种特殊情况?

我认为唯一的方法是获取样式属性的原始值。你这样做是通过以下方式

//will output background: dd97f0
cCell.getAttribute('style');

如果需要,您可以使用此代码段将样式分解为键值对

//give "background: dd97f0", will output "background=dd97f0"
var stylePattern = /(.*?):([^;]*);?/g
while (match = stylePattern.exec(style)) {
    console.log(match[1].trim() + "=" + match[2].trim());
}