kendo编辑器:防止keydown无法正常工作

时间:2017-06-02 15:44:17

标签: kendo-ui editor onkeydown

如果kendo编辑器主体具有一定的高度(限制编辑器字段的最大高度),我想阻止按ENTER键。但我的尝试都没有奏效。

<textarea data-role="editor"
          data-bind="events: { keydown: onEditorKeyDown }">
</textarea>

viewModel.onEditorKeyDown = function (e) {
            var key = e.keyCode;
            if (key == 13) {
                var editor = e.sender;
                var body = editor.body;
                var height = body.scrollHeight;
                if (height > 195) {
                    ?? //tried e.preventDefault(), return false etc.
                }
            }
        };

1 个答案:

答案 0 :(得分:1)

我设法找到了两个解决方案。一个是肮脏的黑客,其他不符合您的要求100%。但两者都或多或少地执行所需要的工作。

通过嵌入式编辑器insertParagraph命令添加新段落,该命令会覆盖默认的keydown逻辑。因此,第一个解决方案是使用keydownkeyup事件临时覆盖此命令,如下所示:

<textarea data-role="editor" 
    data-bind="events: { keydown: onEditorKeyDown, keyup: onEditorKeyUp }">
</textarea>
// this should probably be moved to viewModel, it's here for demo puproses only
var savedCommand;
var viewModel = kendo.observable({
    html: null,
    isVisible: true,
    onChange: function() {
        kendoConsole.log("event :: change (" + kendo.htmlEncode(this.get("html")) + ")");
    }
});

viewModel.onEditorKeyDown = function (e) {
        var key = e.keyCode;
        if (key == 13) {
            var editor = e.sender;
            var body = editor.body;
            var height = body.scrollHeight;
            if (height > 195) {
                savedCommand = editor.toolbar.tools.insertParagraph.command;
                editor.toolbar.tools.insertParagraph.command = function() {};
            }
        }
    };

viewModel.onEditorKeyUp = function (e) {
        var key = e.keyCode;
        if (key == 13) {
            if (savedCommand) {
                var editor = e.sender;
                editor.toolbar.tools.insertParagraph.command = savedCommand;
                savedCommand = undefined;
            }
        }
    };

kendo.bind($("#example"), viewModel);

这很好用,但看起来有点难看。

其他解决方案是根据需要执行编辑器撤消命令。它也有效,但空行总是闪烁一下:

<textarea data-role="editor"
    data-bind="events: { keyup: onEditorKeyUp }"></textarea>
var viewModel = kendo.observable({
    html: null,
    isVisible: true,
    onChange: function() {
        kendoConsole.log("event :: change (" + kendo.htmlEncode(this.get("html")) + ")");
    }
});

viewModel.onEditorKeyUp = function (e) {
        var key = e.keyCode;
        if (key == 13) {
            var editor = e.sender;
            var body = editor.body;
            while (body.scrollHeight > 195) {
                editor.exec('undo');
            }
        }
    };

kendo.bind($("#example"), viewModel);
UPD:我发现事件更好的解决方案。您可以使用execute活动,请参阅http://docs.telerik.com/kendo-ui/api/javascript/ui/editor#events-execute

然后检查条件并按命令名称过滤以取消插入新段落:

execute: function(e) {
  alert(e.name);
  e.preventDefault();
}