前言
最近使用blockly时发现FieldTextInput无法通过json去限制输入框的字符数,又不想在校验器里去限制,所以只好自己添加一下。
实现
首先同fieldNumber类似在json中填写最大限制,所以添加maxlength字段:
{
"type": "textInput",
"message0": "内容 %1",
"args0": [{
"type": "field_input",
"name": "text",
"text": "",
"maxlength": 5 // 新增字段
}]
}
然后就是修改FieldTextInput的原型方法:
import * as Blockly from 'blockly/core';
Blockly.FieldTextInput.prototype.configure_ = function (a) {
Blockly.FieldTextInput.superClass_.configure_.call(this, a);
"number" == typeof a.maxlength && (this.maxlength = a.maxlength); // 接收maxlength
"boolean" == typeof a.spellcheck && (this.spellcheck_ = a.spellcheck);
};
Blockly.FieldTextInput.prototype.widgetCreate_ = function () {
var a = Blockly.WidgetDiv.DIV;
Blockly.utils.dom.addClass(this.getClickTarget_(), "editing");
var b = document.createElement("input");
b.className = "blocklyHtmlInput";
b.setAttribute("spellcheck", this.spellcheck_);
b.setAttribute("maxlength", this.maxlength); // 写入maxlength
var c = this.workspace_.scale,
d = this.constants_.FIELD_TEXT_FONTSIZE * c + "pt";
a.style.fontSize = d;
b.style.fontSize = d;
d = Blockly.FieldTextInput.BORDERRADIUS * c + "px";
if (this.fullBlockClickTarget_) {
d = this.getScaledBBox();
d = (d.bottom - d.top) / 2 + "px";
var e = this.sourceBlock_.getParent()
? this.sourceBlock_.getParent().style.colourTertiary
: this.sourceBlock_.style.colourTertiary;
b.style.border = 1 * c + "px solid " + e;
a.style.borderRadius = d;
a.style.transition = "box-shadow 0.25s ease 0s";
this.constants_.FIELD_TEXTINPUT_BOX_SHADOW &&
(a.style.boxShadow =
"rgba(255, 255, 255, 0.3) 0px 0px 0px " + 4 * c + "px");
}
b.style.borderRadius = d;
a.appendChild(b);
b.value = b.defaultValue = this.getEditorText_(this.value_);
b.untypedDefaultValue_ = this.value_;
b.oldValue_ = null;
this.resizeEditor_();
this.bindInputEvents_(b);
return b;
};
结语
目前只想到了这种方式,若是有更好的实现欢迎讨论。