一个小巧、可定制、移动友好的颜色选择器插件,允许您在提供的图像中选择像素颜色值
这个颜色选择器目前支持两种颜色模型(RGB和HEX),并与jQuery和Vanilla JavaScript完美配合。当你希望用户能够从他们已经添加到页面的图像中选择颜色时,这是理想的选择。
1.下载插件并将主JavaScript导入到文档中。
<!-- jQuery Version --> <script src="/path/to/cdn/jquery.min.js"></script> <script src="/path/to/jquery.tinycolorpicker.min.js"></script> <!-- Vanilla JavaScript --> <script src="/path/to/tinycolorpicker.min.js"></script>
2.为图像颜色选择器构建HTML。
<div id="colorPicker"> <a class="color"><div class="colorInner"></div></a> <div class="track"></div> <ul class="dropdown"><li></li></ul> <input type="hidden" class="colorInput"/> </div>
3.为图像颜色选择器设置样式的示例CSS。不要忘记替换轨道
班
#colorPicker { width: 30px; height: 30px; position: relative; clear: both; margin: 80px auto 20px; } #colorPicker .track { background: #EFEFEF url(example.png) no-repeat 50% 50%; height: 150px; width: 150px; padding: 10px; position: absolute; cursor: crosshair; float: left; left: -71px; top: -71px; display: none; border: 1px solid #ccc; z-index: 10; -webkit-border-radius: 150px; -moz-border-radius: 150px; border-radius: 150px; } #colorPicker .color { width: 25px; height: 25px; padding: 1px; border: 1px solid #ccc; display: block; position: relative; z-index: 11; background-color: #EFEFEF; -webkit-border-radius: 27px; -moz-border-radius: 27px; border-radius: 27px; cursor: pointer; } #colorPicker .colorInner { width: 25px; height: 25px; -webkit-border-radius: 27px; -moz-border-radius: 27px; border-radius: 27px; } #colorPicker .dropdown { list-style: none; display: none; width: 27px; position: absolute; top: 28px; border: 1px solid #ccc; left: 0; z-index: 1000; } #colorPicker .dropdown li{ height: 25px; cursor: pointer; }
4.调用函数锡色拾取器
在顶部容器上,插件将完成其余工作。
// jQuery Version $(document).ready(function(){ var $box = $('#colorPicker'); $box.tinycolorpicker(); }); // The plain javascript api is very similar to the jquery version with some exceptions. // There is no chaining like in the jquery api. // So when you create a instance it will return all methods and properties. var $picker = document.getElementById("colorPicker"), picker = tinycolorpicker($picker);
5.您还可以使用背景URL
选项
var $box = $('#colorPicker',{ backgroundUrl: '/path/to/image', });
6.定义一个后备颜色数组。仅在旧版浏览器上需要。
var $box = $('#colorPicker',{ colors : ["#ffffff", "#A7194B","#FE2712"], });
7.API方法。
// set color picker.setColor("#FF0000"); // convert HEX to RGB picker.hexToRgb(); // convert RGB to HEX picker.rgbToHex(); // close the color picker picker.close();
8.每次选择颜色时都会触发一个功能。
var box = $box.data("plugin_tinycolorpicker"); $box.on("change", function(){ console.log(box.colorRGB); console.log(box.colorHEX); });