随机十六进制颜色生成器+ RGB滑块jquery

时间:2012-03-11 18:15:59

标签: jquery

我在使用此hex随机函数函数传递值(var hex)以生成新颜色时遇到问题。我对事件处理程序并不擅长,所以任何帮助都非常感谢。在此先感谢:)

<body>
 <div id="backgroundColor" style="background:#EEE8CD;">
   <p>R:
     <span class="wrap_red"><input class="r ch" type="range" min="0" max="255" /></span>
     <input type="number" min="0" max="255" />
   </p>
   <p>G:
     <span class="wrap_green"><input class="g ch" type="range" min="0" max="255" /></span>
     <input type="number" min="0" max="255" />
   </p>
   <p>B:   
     <span class="wrap_blue"><input class="b ch" type="range" min="0" max="255" /></span>
     <input type="number" min="0" max="255" />
   </p>
   <table id="tableRGB">
     <tr>
         <td>
           <strong>RGB: </strong>#<span class="result">567890</span>
         </td>
         <td>
           <strong> Hexadecimal: </strong>#<input type="number">
         </td>
    </tr>  
    </table> 
   <button type="button" id="button" onclick="click();">Generate</button>

$(document).ready(function () {  
    var Color = {
    defaults: {
    // Predefined hex codes that cant be used as random colors
    // All must be prefixed with the '#' indicator
    predef: [],

    // Maximum & Minimum random range values
    rangeMax: 255,
    rangeMin: 0,

    // Upper and lower level values that must be 
    // passed for random color acceptance
    //
    // By setting levelUp: 200, levelDown: 100; Neutral
    // colors like White, Gray, and Black can be somewhat weeded
    // out and your random colors will be full spectrum based.
    // Note*: Doing so increases likely hood of recursion
    levelUp: -1,
    levelDown: 256,

    // Recursion handlers
    recursionLimit: 15,
    recursion: function () {
        throw 'Recursion Error in Random Color Generator, ' +
            'too many tries on finding random color, ' +
            '[Limit ' + this.recursionLimit + ']';
    }
},

// Caching of random colors
stack: {},

// Returns a random color in hex code form, and caches
// find in the stack.

rand: function () {
    var defaults = this.defaults;
    return defaults.rangeMin + Math.floor(Math.random()*(defaults.rangeMax+1));
},
random: function (i) {
    var self = this,
        defaults = self.defaults,
        r = self.rand(),
        g = self.rand(),
        b = self.rand(),
        hex = self.rgb2hex(r, g, b),
        levels = true;

    // Check for recursion
    if (i === undefined || typeof i !== 'number') i = 0;
    else if (i++ > defaults.recursionLimit) return defaults.recursion();

    // Color already used, try another one
    if (self.stack[hex]) hex = self.random(i);

    // Ensure one of the vals is above levelUp and another is below levelDown
    // Check defaults comments for better understanding
    levels = !!(
        (r > defaults.levelUp || g > defaults.levelUp || b > defaults.levelUp) &&
        (r < defaults.levelDown || g < defaults.levelDown || b < defaults.levelDown)
    );
    if (! levels) hex = self.random(i);

    // Store on stack to help prevent repeat
    self.stack[hex] = [r,g,b];

    // Return hex code in #
    return hex;
}


// Returns hex code
rgb2hex: function (r,g,b) {
    var str = '0123456789ABCDEF';
    return '#' + [
        str.charAt( (r - r % 16) / 16) + str.charAt(r % 16),
        str.charAt( (g - g % 16) / 16) + str.charAt(g % 16),
        str.charAt( (b - b % 16) / 16) + str.charAt(b % 16)
    ].join('');
},

// Returns in array form [red, green, blue]
hex2rgb: function (hex) {
    if (hex.substr(0,1) === '#')
        hex = hex.substr(1);

    // Use the stack if possible to reduce processing
    return this.stack['#' + hex] ? this.stack['#' + hex] : 
        hex.length === 6 ? [
            parseInt(hex.substr(0, 2), 16),
            parseInt(hex.substr(2, 2), 16),
            parseInt(hex.substr(4, 2), 16)
        ] : hex.length === 3 ? [
            parseInt(hex.substr(0, 1), 16),
            parseInt(hex.substr(1, 1), 16),
            parseInt(hex.substr(2, 1), 16)
        ] : [];
}
   };
//Random color generator button
$('#generate').click( function () {
    $('div').each(function() {
        var th = $(this);
        hex = th.css('backgroundColor');
        rgb = hex.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        var red = rgb[1];
        var green = rgb[2];
        var blue = rgb[3];

        th.find('.r').val(red);
        th.find('.r').parent('span').siblings('input').val(red);
        th.find('.g').val(green);
        th.find('.g').parent('span').siblings('input').val(green);
        th.find('.b').val(blue);
        th.find('.b').parent('span').siblings('input').val(blue);

        $('input').bind('change keyup click', function() {
            if ($(this).hasClass('ch')) {
                $(this).parent('span').siblings('input').val($(this).val());
            }
            else {
                if ($(this).val() > 255) 
                    $(this).val(255);
                if ($(this).val() < 0) 
                    $(this).val(0);
                    $(this).siblings('span').find('input').val($(this).val());
            }

            r = parseInt(th.find('.r').val()).toString(16);
            if (r.length == 1) 
                r = '0' + r;

            g = parseInt(th.find('.g').val()).toString(16);
            if (g.length == 1) 
                g = '0' + g;

            b = parseInt(th.find('.b').val()).toString(16);
            if (b.length == 1) 
                b = '0' + b;

            x = r + g + b;

            th.find('.result').html(x);
            th.css('backgroundColor', '#' + x);

        });
    });
});
});

  

1 个答案:

答案 0 :(得分:0)

首先,您不需要onclick="click()",您可以使用jQuery的.click()捕获$('#button').click(function(){/*do stuff*/})$('#button').click(function_name),然后您的代码中会出现一堆错误,jslintjshint可以提供帮助,这就是我看到的错误:

  

错误:第51行第51个问题:预期'{'而不是看到   '一世'。 if(i === undefined || typeof i!=='number')i = 0;

     

第52行问题45:预期'{'而不是看到   '返回'。否则if(i ++&gt; defaults.recursionLimit)返回   defaults.recursion();

     

第55行的问题26:预期'{'而是看到'hex'。   if(self.stack [hex])hex = self.random(i);

     

第63行问题字符19:预期'{'而不是'hex'。   if(!levels)hex = self.random(i);

     

第74行问题1:预期'}'匹配第2行的'{'   而是看到'rgb2hex'。 rgb2hex:function(r,g,b){

     

第74行问题8:缺少分号。 rgb2hex:功能   (r,g,b){

     

第74行的问题字符8:预期'}'匹配第1行的'{'   而是看到':'。 rgb2hex:function(r,g,b){

     

第74行问题10:预期')'而是看到了   '功能'。 rgb2hex:function(r,g,b){

     

第74行问题26:缺少分号。 rgb2hex:功能   (r,g,b){

     

第74行问题27:预计会看到一个声明和   而是看到一个街区。 rgb2hex:function(r,g,b){

     

第74行问题27:停止,无法继续。 (50%   扫描)。隐含的全局:$ 1,r 74,g 74,b 74未使用的变量:颜色   1“准备好”

相关问题