点击时动态更改CSS颜色属性 [英] Change CSS color property dynamically on click

查看:851
本文介绍了点击时动态更改CSS颜色属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数生成随机颜色,我想使用该功能与jQuery的能力 toggleClass 点击。我想为一个单击生成一个独特的颜色,并且如果用户再次点击一个有色的单元格(使它再次白/无色)删除生成的颜色。

I have a function that generates random colors, I want to use that function in conjunction with jQuery's ability to toggleClass on click. I want to generate a unique color to a table cell on click, and to remove the generated color if user clicks on a colored cell again (make it white again/colorless).

HTML表格:

   <div id="container">
        <table id="table">
            <tr>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
            </tr>

        </table>
    </div>

颜色生成功能:

    function getRandomColor() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

为单元格指定颜色:

$( function(){
    $('td').click( function(){
            $(this).css('background-color',getRandomColor);
    });
});


推荐答案

注意使用'rgba (0,0,0,0)'仅适用于某些浏览器(Chrome,但不适用于IE)。这个版本从主体获取颜色以供参考(但是没有 background-color 设置的任何元素都会执行。

Note solutions using 'rgba(0, 0, 0, 0)' only work on some browsers (Chrome, but not IE for instance). This version gets the colour from the body for reference (but any element with no background-colour set will do.

您可以将代码更改为jQuery扩展,称为 toggleRandomColor ,如下所示:

You can change your code to a jQuery extension, called say toggleRandomColor like this:

var blankColor = $('body').css('background-color');
$.fn.toggleRandomColor = function () {
    if ($(this).css('background-color') == blankColor) {
        $(this).css('background-color', getRandomColor);
    } else {
        $(this).css('background-color', '');
    }
};

然后简单地使用它像这样:

and then simply use it like this:

$('td').click(function () {
    $(this).toggleRandomColor();
});

JSFiddle: strong> http://jsfiddle.net/TrueBlueAussie/nmav8d3n/4/

这篇关于点击时动态更改CSS颜色属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆