jquery - 用颜色选择器的颜色填充div

时间:2014-08-05 08:20:50

标签: javascript jquery html paint color-picker

我正在用jQuery和HTML制作一个简单的绘画程序。为此我使用Spectrum颜色选择器(http://bgrins.github.io/spectrum/)。我制作了一个包含数百个16x16正方形(div类像素)的网格,当点击其中一个时,它将填充Spectrum颜色选择器的颜色,但我不知道如何。这是我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" rel="stylesheet" href="css.css" />
<title>Pixel Painter</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><!-- Jquery -->
<script src='jscolor/jscolor.js'></script> <!--Spectrum js-->
<link rel='stylesheet' href='jscolor/jscolor.css' /> <!--Spectrum css-->
</head>
<body>
<input id='colorpicker' />
<script>
$("#colorpicker").spectrum({ //spectrum config
    color: "#f00",
    showPalette: true,
    showInput: true,
    showAlpha: true,
    chooseText: "Pick",
    cancelText: "X",
    togglePaletteOnly: true,
    showPaletteOnly: true,
    togglePaletteMoreText: "More Colors...",
    togglePaletteLessText: "Less Colors...",
        palette: [
            //color palettes for Spectrum
        ]
});
</script>
<br/>
<table border="1" style="background-color:#FFFFFF; border-collapse:collapse;border:1px solid #000000;color:#000000;width:100%" cellpadding="3" cellspacing="0">
    <tr>
        <!-- Grid -->
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
    </tr>
    <tr>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
        <div class="pixel"></div>
    </tr>
<!--... and a lot more <div class="pixel"></div>-->
</table>
</body>
</html>

http://jsfiddle.net/jGb33/

1 个答案:

答案 0 :(得分:2)

你可以这样做:

var color = "#f00";

$("#colorpicker").spectrum({ //spectrum config
  color: "#f00",
  showPalette: true,
  showInput: true,
  showAlpha: true,
  chooseText: "Pick",
  cancelText: "X",
  togglePaletteOnly: true,
  showPaletteOnly: true,
  togglePaletteMoreText: "More Colors...",
  togglePaletteLessText: "Less Colors...",
  palette: [
        //color palettes for Spectrum
  ],
  change: function(colorSelected) {
    color = colorSelected.toHexString();
  }
});

$('.pixel').click(function(){

  $(this).css('background-color' , color);

});

http://jsfiddle.net/jGb33/1/