以十六进制格式JQuery获取DIV的颜色

DRO*_*mes 2 html javascript css jquery

这是我的代码:

function getTraits(trait) {
    $("#"+trait).on("click", function() {
        alert($(this).css('backgroundColor'));
        if (toHex($(this).css('background-color')) != highlightedColor) {
            $("#"+trait).css("background-color", highlightedColor);
            // If the element isn't highlighted, highlight it.
        } else {
            $(this).css("backgroundColor", defaultColor);
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

我试图在用户的点击上切换div上的突出显示.我想获得div的背景颜色,因为为每个div存储一个布尔切换是低效的.所以我想要一个toHex(rgb)功能.我在SO上看到了很多,所以我尝试使用它们,但没有一个能够工作.该alert()放给我看的格式:jQuery是回来时,我给了我rgba(0,0,0,0).我试图修改我发现的正则表达式:

var rgb = rgb.match(/^rgba((\d+),\s*(\d+),\s*(\d+))$/);

这无法使用TypeError : rgb is null.

感谢你给与我的帮助!

For*_*ty3 5

我知道,不是你问题的答案,但你考虑过jQuery的toggleClass()选择吗?

定义一个highlightedCSS类:

DIV.default { background-color: whitesmoke; }
DIV.highlighted { background-color: yellow; }
Run Code Online (Sandbox Code Playgroud)

然后当用户点击你的DIV时:

function getTraits(trait) {
    $("#"+trait).on("click", function() {
        // Toggle both classes so as to turn one "off" 
        // and the other "on"
        $(this).toggleClass('default');
        $(this).toggleClass('highlighted');

        // Ensure we have at least one class (default)
        var hasOne = $(this).hasClass('highlighted') || $(this).hasClass('default');
        if (!hasOne) {
          $(this).addClass('default');
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

  • 这非常有效,但你可以在没有`!important`的情况下做到这一点吗?根据我的经验,当我把太多的`!important`s'放入时,我的代码就无法读取. (2认同)