wordpress 拾色器(Color Picker)

        在WordPress中任意地方添加一个颜色选择器(color picker/拾色器)只需要三行代码就能解决:

<?php wp_enqueue_style( 'wp-color-picker' );//加载拾色器样式 ?>
<input type="text" class="lunbo-color-picker"  ><!--拾色器-->
<script>
  jQuery( '.lunbo-color-picker' ).wpColorPicker();//颜色选择器
</script>

  上面是最简单的方法,当然在某些位置加载的时候可能存在一些问题。

比如不存在 jQuery( ... ).wpColorPicker()方法,因为缺少 拾色器的script 在样式前面加上 wp_enqueue_script( 'wp-color-picker' );就对了。

        当然可以通过js设置自定义参数,如下:

    var lunboOptions = {
        change: function(event, ui){ //每当颜色改变为有效颜色时执行此回调。
            var lunbocolor=ui.color.toString();//获取改变后新的颜色值(自己看的)
            jQuery("#<?php echo $this->get_field_id('lunbo_background_color'); ?>").val(lunbocolor);
            jQuery('.lunbo-color-picker').trigger('change');//只有触发change事件才会更新
        },
        // a callback to fire when the input is emptied or an invalid color
        clear: function() {},
        // hide the color picker controls on load
        hide: true,
        // show a group of common colors beneath the square
        // or, supply an array of colors to customize further
        palettes: true
    };
    jQuery( '.lunbo-color-picker' ).wpColorPicker(lunboOptions);//颜色选择器

以上参考New Color Picker in WP 3.5:https://make.wordpress.org/core/2012/11/30/new-color-picker-in-wp-3-5/

具体实现方式可以自行查看源码文件:/wp-admin/js/color-picker.js

其中包含一些参数,ui.color.toString() 就是我在源码中寻找到的方法。

    最后完整代码应该是这样的:

<?php
    wp_enqueue_script( 'wp-color-picker' );
    wp_enqueue_style( 'wp-color-picker' );
?>

<input type="text" class="lunbo-color-picker" >
<script>
    var lunboOptions = {
        change: function(event, ui){
            var lunbocolor=ui.color.toString();
            jQuery("#<?php echo $this->get_field_id('lunbo_background_color'); ?>").val(lunbocolor);
            jQuery('.lunbo-color-picker').trigger('change');//只有触发change事件才会更新
        },
        //具体参数自行添加
    };
    jQuery( '.lunbo-color-picker' ).wpColorPicker(lunboOptions);//图片选择器

         附上一个简单的拾色器插件制作:https://www.wpdaxue.com/use-wordpress-color-picker-api.html

原文地址:https://www.cnblogs.com/mengwangchuan/p/7126684.html