ew-color-picker

This is a flexible, highly customizable color picker written in javascript.

Usage scenarios

This color picker is suitable for small and medium-sized projects, such as theme switching. Unlike the color selector component in the component library, its configuration is autonomous and customized according to user needs.

advantages

Html5’s native color pickers don’t look good, and component library color pickers aren’t flexible enough, so this color picker was born.

Let’s start with a simple example:

<! - Introduce CSS styles for color pickers --><link rel="stylesheet" href="https://www.unpkg.com/ew-color-picker/dist/ew-color-picker.min.css">
  <! -- Introducing plugin JavaScript-->
  <script src="https://www.unpkg.com/ew-color-picker/dist/ew-color-picker.min.js"></script>
Copy the code

Then place an element in the page:

  <div></div>
Copy the code

In javascript, all we need is the following code:

   const color = new ewColorPicker('div');
Copy the code

As a result, a simple color picker appears on the page. Most people may not like instantiation, so we provide a way to create it:

  const color = ewColorPicker.createColorPicker('div');
Copy the code

This also creates an instance of a color picker.

In fact, the import link shown above will automatically import the latest version of JS. Use the latest version of JS to make sure we don’t have bugs or new features in use. As long as I’m here, The plugin updates itself, adding everything you can think of.

Tips: It should also be noted that in order to conform to one color selector for one instance, when multiple DOM elements are passed in, the first DOM element is also instantiated. For example, if you pass in div elements, if you have multiple div elements on the page, you actually get multiple div elements inside the color picker, but the first div element is always instantiated. If we wanted to instantiate more than one color selector, we could use it as follows

   const elements = document.querySelectorAll('div');
   elements.forEach(item= > new ewColorPicker(item));
Copy the code

We also provide a method getDefaultConfig to get the default configuration object for the color picker instance. As follows:

  ewColorPicker.getDefaultConfig();
Copy the code

Also note that the dom element passed in cannot be a special element like ‘HTML ‘,’head’,’body’,’meta’,’title’,’link’,’style’, or ‘script’, otherwise the plugin will give you an error on the console.

Tips: The latest version 1.7.1 allows the addition of the body element, although it is still not recommended. This addition is a bit buggy.

These are the simplest ways to use them, and it may not be intuitive, but here’s a simple example:

demo1

Looking at this, one might wonder, how can this be flexible and highly customizable? Don’t worry, let’s get on with it.

Custom Configuration

Let’s look at a configuration object like this:

{
    el:'.demo2'.// Bind the dom element of the selector
      alpha:true.// Whether to enable transparency
      hue:false.// Whether to turn on tone
      size: {width:100.height:50
      },// The color selector type has four string values: normal,medium,small,mini or a custom width and height for an object. If you want to customize the width and height, the minimum width and height is 25px
      predefineColor: ['# 223456'.'rgba (122,35,77. 5)'].// The predefined color is an array
      disabled:false.// Whether to disable all clicks
      defaultColor:'#eeff22'.// Default color
      pickerAnimation:'opacity'.// or 'height' to animate the color picker panel
      pickerAnimationTime:300.// Animation execution time, default is 200, maximum animation time is 10000
      sure:function(color){
          console.log(color);
      },// Click the ok callback button
      clear:function(){
          console.log(this)},// Click the empty button callback
      togglePicker:(el,flag,context) = > {
        console.log('Current root element',el);
        console.log('Current Color selector instance object',context);
        if(flag){
            console.log("opened");
        }else{
            console.log("closed"); }},// Click the color block event callback. Note that hasBox must be set to true to trigger the event
      isLog:false.// Whether to enable information printing. The default is true if no value is specified
      changeColor:(color) = > {
        console.log('Triggered when color value changes :',color);
      },
      hasBox:true // The default is true, or false, indicating whether the color picker is displayed
      isClickOutside:true.// Defaults to true, or is set to false, indicating whether clicking outside of the color picker area is allowed to close the color picker
      hasClear:true.// Whether to display the empty button. Default is true
      hasSure:true.// Whether to display the ok button, the default is true, false is not recommended
      hasColorInput:true.// Whether to display input fields. The default value is true. False is not recommended
      boxDisabled:true.// Default is false, set to true and hasBox is true to disallow clicking on the color block to open the color picker
      openChangeColorMode:true.// Whether to enable color switching mode. Note that alpha and Hue must be set to true to enable this mode
      hueDirection:"horizontal".// Vertical: Indicates whether the hue column is displayed horizontally or vertically by default
      alphaDirection:"horizontal".// Or vertical, the default is vertical layout, indicating whether the transparency column is displayed horizontally or vertically
      lang:"zh".// or en, which indicates whether to enable Chinese mode or English mode
      clearText:"Empty".// Empty the button text. If you want to customize the value, set userDefineText to true
      sureText:"Sure".// Determine the button text. If you want to customize this value, you need to set userDefineText to true
      userDefineText:false.// The default is false. When set to true, the switching of the lang property is invalid
}

Copy the code

Let’s start with the first hue configuration property. Maybe we’ll see a complete configuration color picker that looks something like this:

Let’s focus on what each piece represents:

Hue’s attribute controls the right – most color column, which is displayed by default.

Tips: If it is a custom configuration, then the element passed in is an EL attribute in the configuration object. For example, we only need a color palette. So we can write the following code:

  const color = new ewColorPicker({
      el:'div'.hue:false
  })
Copy the code

This gives us a color picker like this:

As you can see, it’s a bad choice to have a red palette to choose from, but no matter, we provide the updateColor method to manually change the color value. The code is as follows:

   //color is the instantiated color picker instance
   color.updateColor("#0ff");
Copy the code

Of course, this method is used only if the color selector panel must be displayed in the center, and the parameter passed must be a correctly formatted color, otherwise it will give an error message on the console, and will not take effect.

See the following example:

demo

Ok, let’s move on to the second configuration property alpha, which obviously controls the opacity of the transparency column. It’s not displayed by default. For example, we could modify it like this:

   const color = new ewColorPicker({
      el:'div'.hue:false.alpha:true
  })
Copy the code

This code results in a color picker like the one shown below:

Many of you may have noticed that the hasBox property is set in the previous example. Its default value is true, which obviously controls the implicit color of the color block. If this value is false, the color palette is displayed by default. So, we provide two methods, openPicker and closePicker, to manually close the color palette (PS: click outside the target element area to close it later). As follows:

 //color is the color picker instance
 color.openPicker(openPickerAni);The parameters are string values of height or opacity, which are equivalent to subsequent openPickerAni configuration properties
 color.closePicker(openPickerAni);
Copy the code

Let’s look at the following example of manually controlling the color picker off:

demo

In the example above, you may have noticed the isClickOutside property, which is also a Boolean value and defaults to true, meaning that clicking on an area outside the color palette closes the color palette. Consider the following example:

<div id="demo"></div>
<button type="button" id="openClickOutsideBtn">Click event on | off target area element</button>
Copy the code
button {
  float:right;
}
Copy the code
const color = new ewColorPicker({
  el:"#demo".isClickOutside:false
})
document.getElementById("openClickOutsideBtn").onclick = function(){ color1.config.isClickOutside = ! color1.config.isClickOutside; }Copy the code

demo

Moving on, we can see the size property, which can be a string value or an object. The string value is one of the four normal,medium,small,mini, or a custom object. Height :25}, the default is normal. Of course, if the hasBox property is set to true, the box elements are not displayed. What is the use of setting this value? The following openPickerAni property is the same as the openPicker method and hasBox must be set to true, which is why it is set to true by default. Let’s take a look at the following example:

    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
Copy the code
    const colors = document.querySelectorAll('div');
    const colorConfigs = [
        {
            size:"normal"
        },
        {
            size:"medium"
        },
        {
            size:"small"
        },
        {
            size:"mini"
        },
        {
            size: {width:25.height:25}}]; colors.forEach((item,index) = > {
        new ewColorPicker({
            el:item, ... colorConfigs[index] }) })Copy the code

You can see the running effect as shown below:

Let’s move on to the next property, predefineColor. As the name suggests, this property is an array representing predefined colors. Each array entry must be a qualified color value or it won’t be rendered to the color picker. Consider the following example:

  <div></div>
Copy the code
    const color = new ewColorPicker({
        el:"div".predefineColor: ["#2396ef"."#fff"."Rgba (134,11,12,1)"."# 666"].alpha:true
    })
Copy the code

Then we can see something like the following:

Let’s move on to the next property, disabled, which disallows clicking on the box element to open the color palette, meaning that if hasBox is false, ignore this property.

Tips: In the future, we might consider adding a color panel with a no click event, etc.

There’s nothing to talk about here, so I’m not going to give you an example. Let’s move on to the next property, defaultColor, which is the color value displayed by default. If a color value is detected that does not conform to the format, an error message is presented on the console, as in this example:

  <div></div>
Copy the code
    const color = new ewColorPicker({
        el:"div".predefineColor: ["#2396ef"."#fff"."Rgba (134,11,12,1)"."# 666"].alpha:true.defaultColor:"# 123"
    })
Copy the code

As shown below:

Tips: Maybe there is something wrong with the mechanism to check whether the color value is acceptable. It will be improved later.

Let’s move on to the next property, openPickerAni, which has only two values. It’s the same as the one used to manually turn on or off the color picker method, but you can’t set hasBox to false for this property to work.

The same openPicker works for hasBox to be true, which is the callback to clicking on the color block element and takes two callback arguments. El and context, which is the element itself and the instance object of the element itself.

  const color = new ewColorPicker({
     el:"div".openPicker:(el,context) = > {
        / / by the context. Config. Judging pickerFlag is open or closed}})Copy the code

In the same way that clear and Sure are the callbacks of the clear and SURE buttons, you cannot set hasClear and hasSure to false for these callbacks to work because the configuration properties are null clear and sure implicit, respectively. The hasClear callback argument is defaultColor, null if null, and the element’s own instance object context. The sure callback argument is the color value and the element itself instance object. Please write it as follows:

   const color = new ewColorPicker({
     el:"div".clear:(defaultColor,context) = > {
        console.log(defaultColor,context);
     },
     sure:(color,context) = > {
       console.log(color,context); }})Copy the code

In addition to these two callbacks, we have added another callback, the changeColor function, which, as the name implies, is triggered when the color value changes, such as clicking on the level bar to change the color, clicking on the transparency bar to change the opacity, and so on. See the code below:

   const color = new ewColorPicker({
     el:"div".changeColor:(color) = > {
         // When the color value is changed, the callback argument is the changed color value}})Copy the code

There is also an isLog property, which defaults to true, meaning that some information will be printed on the console, please ignore this property, haha, consider setting it to false later.

The last one is the hasColorInput property, which indicates whether to display the input box. This is useful for custom input boxes (such as those bound to element UI’s input box) and color picker bindings, and false is not recommended if you want to use it.

Let’s look at an example as follows:

  <div></div>
Copy the code
    const color = new ewColorPicker({
        el:"div".hasColorInput:false.hasSure:false.hasBox:false.hasClear:false.alpha:true
    })
Copy the code

The effect is shown below:

At present, the latest version is 1.6.8, and we will consider adding more functions in the future. As long as you have requirements, please tell me, I think it is reasonable to add, if you think this color picker can help you, also hope to give a star, source code.

For more information, please refer to the official website of the document and the code cloud site.

Tips: If Github is too slow to access, check out the code Cloud website.

Finally, if I have time later, I will consider writing an article to analyze the implementation principle of this color picker.

Update log

ew-color-picker

I want to advertise that I’m playing with typescript1, playing with typescript2, and creating a mini version of the compiler from scratch for basic front-end applications. Thank you.