阅读 311

颜色控件--@Simonwep / pickr

简介

平面,简单,多主题,响应和可黑客的颜色选择库。 没有依赖,就没有jQuery。 兼容所有CSS框架,如Bootstrap, Materialize。 支持alpha通道,rgba, hsla, hsva和更多!

安装(Install)

$ npm install @simonwep/pickryarn add @simonwep/pickr

主题(Themes)

  • 有三种主题:ClassicMonolithNano

image.png

// One of the following themes
import '@simonwep/pickr/dist/themes/classic.min.css';   // 'classic' theme
import '@simonwep/pickr/dist/themes/monolith.min.css';  // 'monolith' theme
import '@simonwep/pickr/dist/themes/nano.min.css';      // 'nano' theme复制代码

使用(Usage)

  • new PickrPickr.create都可以创建实例。

import React, { Component } from 'react';
import Pickr from '@simonwep/pickr';
import '@simonwep/pickr/dist/themes/nano.min.css'; // 'nano' theme

class ColorPicker extends Component {
  componentDidMount() {
    const pickr = new Pickr({
      el: '.color-picker',
      theme: 'nano',
      comparison: false,
      lockOpacity: true,
      default: '#42445a',
      swatches: ['#F44336', '#E91E63', '#9C27B0', '#673AB7'],
      components: {
        preview: false,
        opacity: false,
        hue: true,
        interaction: {
          input: true,
        },
      },
    });

    pickr.on('change', (color, source, instance) => {
      pickr.options.default = color.toHEXA().toString();
      console.log('change', color.toHEXA().toString(), source, instance);
    });
  }

  render() {
    return (
      <div>
        <h2>颜色控件</h2>
        <div className="color-picker" />
      </div>
    );
  }
}

export default ColorPicker;复制代码

效果

image.png

参数(Options)

const pickr = new Pickr({

    // Selector or element which will be replaced with the actual color-picker.
    // Can be a HTMLElement.
    el: '.color-picker', // 挂在的元素,pickr会把该元素替换

    // Where the pickr-app should be added as child.
    container: 'body',

    // Which theme you want to use. Can be 'classic', 'monolith' or 'nano'
    theme: 'classic',

    // Nested scrolling is currently not supported and as this would be really sophisticated to add this
    // it's easier to set this to true which will hide pickr if the user scrolls the area behind it.
    closeOnScroll: false,

    // Custom class which gets added to the pcr-app. Can be used to apply custom styles.
    appClass: 'custom-class',

    // Don't replace 'el' Element with the pickr-button, instead use 'el' as a button.
    // If true, appendToBody will also be automatically true.
    useAsButton: false,

    // Size of gap between pickr (widget) and the corresponding reference (button) in px
    padding: 8,

    // If true pickr won't be floating, and instead will append after the in el resolved element.
    // It's possible to hide it via .hide() anyway.
    inline: false,

    // If true, pickr will be repositioned automatically on page scroll or window resize.
    // Can be set to false to make custom positioning easier.
    autoReposition: true,

    // Defines the direction in which the knobs of hue and opacity can be moved.
    // 'v' => opacity- and hue-slider can both only moved vertically.
    // 'hv' => opacity-slider can be moved horizontally and hue-slider vertically.
    // Can be used to apply custom layouts
    sliders: 'v',

    // Start state. If true 'disabled' will be added to the button's classlist.
    disabled: false,

    // If true, the user won't be able to adjust any opacity.
    // Opacity will be locked at 1 and the opacity slider will be removed.
    // The HSVaColor object also doesn't contain an alpha, so the toString() methods just
    // print HSV, HSL, RGB, HEX, etc.
    lockOpacity: false,

    // Precision of output string (only effective if components.interaction.input is true)
    outputPrecision: 0,

    // Defines change/save behavior:
    // - to keep current color in place until Save is pressed, set to `true`,
    // - to apply color to button and preview (save) in sync with each change
    //   (from picker or palette), set to `false`.
    comparison: true,

    // Default color. If you're using a named color such as red, white ... set
    // a value for defaultRepresentation too as there is no button for named-colors.
    default: '#42445a', // 默认颜色

    // Optional color swatches. When null, swatches are disabled.
    // Types are all those which can be produced by pickr e.g. hex(a), hsv(a), hsl(a), rgb(a), cmyk, and also CSS color names like 'magenta'.
    // Example: swatches: ['#F44336', '#E91E63', '#9C27B0', '#673AB7'],
    swatches: null, // 设置样本板块展示的颜色

    // Default color representation of the input/output textbox.
    // Valid options are `HEX`, `RGBA`, `HSVA`, `HSLA` and `CMYK`.
    defaultRepresentation: 'HEX',

    // Option to keep the color picker always visible.
    // You can still hide / show it via 'pickr.hide()' and 'pickr.show()'.
    // The save button keeps its functionality, so still fires the onSave event when clicked.
    showAlways: false,

    // Close pickr with a keypress.
    // Default is 'Escape'. Can be the event key or code.
    // (see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
    closeWithKey: 'Escape',

    // Defines the position of the color-picker.
    // Any combinations of top, left, bottom or right with one of these optional modifiers: start, middle, end
    // Examples: top-start / right-end
    // If clipping occurs, the color picker will automatically choose its position.
    // Pickr uses https://github.com/Simonwep/nanopop as positioning-engine.
    position: 'bottom-middle',

    // Enables the ability to change numbers in an input field with the scroll-wheel.
    // To use it set the cursor on a position where a number is and scroll, use ctrl to make steps of five
    adjustableNumbers: true,

    // Show or hide specific components.
    // By default only the palette (and the save button) is visible.
    components: {

        // Defines if the palette itself should be visible.
        // Will be overwritten with true if preview, opacity or hue are true
        palette: true,

        preview: true, // Display comparison between previous state and new color
        opacity: true, // Display opacity slider
        hue: true,     // Display hue slider

        // show or hide components on the bottom interaction bar.
        interaction: { // 控制面板的显示内容

            // Buttons, if you disable one but use the format in default: or setColor() - set the representation-type too!
            hex: false,  // 是否显示HEX按钮
            rgba: false, // 是否显示RBGA按钮
            hsla: false, // 是否显示HSLA按钮
            hsva: false, // 是否显示HSVA按钮
            cmyk: false, // 是否显示CMYK按钮

            input: false, // 是否显示输入框
            cancel: false, // 是否显示’取消‘按钮
            clear: false, // 是否显示’清除‘按钮
            save: false,  // 是否显示’保存‘按钮
        },
    },

    // Translations, these are the default values.
    i18n: {

        // Strings visible in the UI
        // 修改界面显示文本
       'ui:dialog': 'color picker dialog',
       'btn:toggle': 'toggle color picker dialog',
       'btn:swatch': 'color swatch',
       'btn:last-color': 'use previous color',
       'btn:save': 'Save', // 保存按钮文本
       'btn:cancel': 'Cancel',
       'btn:clear': 'Clear',

       // Strings used for aria-labels
       'aria:btn:save': 'save and close',
       'aria:btn:cancel': 'cancel and close',
       'aria:btn:clear': 'clear and close',
       'aria:input': 'color input field',
       'aria:palette': 'color selection area',
       'aria:hue': 'hue selection slider',
       'aria:opacity': 'selection slider'
    }
});复制代码
  • 通过实例直接修改参数,如:默认颜色

pickr.options.default = color.toHEXA().toString(); // 改变默认颜色复制代码

事件(Events)

image.png

pickr.on('init', instance => {
    console.log('Event: "init"', instance);
}).on('hide', instance => {
    console.log('Event: "hide"', instance);
}).on('show', (color, instance) => {
    console.log('Event: "show"', color, instance);
}).on('save', (color, instance) => {
    console.log('Event: "save"', color, instance);
}).on('clear', instance => {
    console.log('Event: "clear"', instance);
}).on('change', (color, source, instance) => {
    console.log('Event: "change"', color, source, instance);
}).on('changestop', (source, instance) => {
    console.log('Event: "changestop"', source, instance);
}).on('cancel', instance => {
    console.log('Event: "cancel"', instance);
}).on('swatchselect', (color, instance) => {
    console.log('Event: "swatchselect"', color, instance);
});复制代码
以change为例
// color 颜色,并提供颜色格式转换方法
// source 来源
// instance 实例
pickr.on("change", (color, source, instance) => {
    console.log(color, source, instance);
});复制代码
  • 三个参数打印结果

image.png

  • 颜色转换,以HEX为例(#xxxxxx)

函数直接转换出来时三个值,并不是我们想要#xxx的格式

image.pngpickr有重写了toString()方法,可以格式化,HEXA、CMYK、HSLA、HSVA、RGBA都可以。

image.png

踩坑

  • 同样的代码在CodeSandbox上面运行没问题,依赖版本跟项目一致,就是不显示出来。

image.png

image.png

  • 项目中没有效果

image.png

  • 原因:样式没有导入

项目里面webpack.config.js做了限制,导致css没有成功引入进去

image.png

image.png

结束

  • 更多内容直接看官方文档,这里只是列出基本使用方法以及自己在开发中用到的部分


作者:Bellet
链接:https://juejin.cn/post/7031507600994893832


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐