如何在 knockout.JS 中使用颜色选择器设置 'style:color'

How to set 'style:color' with colorpicker in knockout.JS

我想用颜色选择器设置文本的颜色。找到了一个不错的小程序,带有一个敲除绑定处理程序,但无法使其工作。

HTML:

<div class="myPicker" data-bind="jqColorPicker: coverTextColor, colorPickerOptions: { value: coverTextColor}"></div>
<span class="title" data-bind="text: title, style: { color: coverTextColor}">blahblah</span>

绑定处理程序和视图模型:

ko.bindingHandlers.jqColorPicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {

        // set default value
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).val(value);

        //initialize datepicker with some optional options
        var options = allBindingsAccessor().colorPickerOptions || {};
        $(element).colorPicker(options);

        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($(element).val());
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).colorPicker("destroy");
        });

    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).val(value);
        $(element).change();
    }
};


viewModel = function(){
    var self = this;
    self.coverTextColor = ko.observable('green');
    self.title = ko.observable('Hi there!');
};

ko.applyBindings( new viewModel() );

感谢任何帮助。

Fiddle 这里:http://jsfiddle.net/AsleG/hmLbb9c0/2/

一个div既没有change事件,也不能用jQuery.val()方法读取它的内容。

您应该使用输入字段的文档 states,并且单独进行更改后您的代码就可以工作。

http://jsfiddle.net/48evdyvx/1/