0

我想将敲除属性绑定到 svg 文本元素的长度,以便在每次更改文本时设置它。我从这样的事情开始:

ko.bindingHandlers.length = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        var width = element.getComputedTextLength();
        valueAccessor()(width);
        element.onchange = function() {
            var newWidth = element.getComputedTextLength();
            valueAccessor()(newWidth);
        };
    }
};

和 svg 元素

<text data-bind="text: text, length: labelLength" x="0" y="0" fill="black">Hello World</text> 

jsfiddle 在这里http://jsfiddle.net/9vWhD/

知道最好的方法吗?

4

1 回答 1

0

如果要在文本更改时设置元素的宽度,可以使用计算出的 observable(小提琴:http: //jsfiddle.net/9vWhD/3/):

var model = function(){
    this.text = ko.observable("Hello World");
    this.labelLength = ko.computed(function(){
        return this.text().length * 10;
    });
    this.changeText = function(){
        this.text("This is some much longer text");
    }
}

或者您想在设置文本后获取文本元素的宽度?如果是这种情况,您可以像这样更改自定义绑定(小提琴:http: //jsfiddle.net/9vWhD/6/):

ko.bindingHandlers.textSetLength = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        $(element).text(valueAccessor()());
        var width = $(element)[0].getBoundingClientRect().width;
        this.labelLength(width);
    }
};
于 2013-11-12T12:18:24.917 回答