我正在使用javascript将类分配给某些元素,从而为某个网站创建样式表。无论出于何种原因,某些“td”元素都会使用怪异的类分配和内联样式,因此我遍历它们,清理它们并分配适当的类名称以在外部样式表中进行引用。

我没有访问网站本身的权限(也没有更改任何内容的管理权限),所以我使用Firefox的Fashionable和Greasemonkey(加上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());
}

07-26 09:29
查看更多