dijit.form.TextBox 根据最后的选择在单击一个 buton 时添加字符串



即使在dijit.form.TextBox中失去焦点后,如何保持光标位置?我的表单中有文本框和按钮。当我单击按钮时,我希望在该文本框中以我保留的特定光标位置添加一些文本。

我想要这样的东西:http://jsfiddle.net/NE4Ev/6/但这在IE浏览器中不起作用。有人可以帮忙吗?

侦听 TextBox 的 onblur 事件以保存光标位置:

textBox.on("blur", function() {
    var start = this.textbox.selectionStart,
        end = this.textbox.selectionEnd;
    this.set("cursorPosition", [start, end]);
});

您可以使用该位置在光标位置插入一些文本,还可以恢复光标位置,当通过调用 textBox.focus() 以编程方式将焦点返回到文本框时,例如当用户单击按钮时:

textBox.on("focus", function() {
    var cursorPosition = this.get("cursorPosition");
    if(cursorPosition) {            
        this.textbox.setSelectionRange(cursorPosition[0], cursorPosition[1]);                                          
    }
});

参见jsFiddle的工作示例:http://jsfiddle.net/phusick/rryEg/

我已经修改了 phusick 的答案以满足您的需求。

但是一旦您了解了小部件上的客户选择,这里就真的没有什么可做的了。

.HTML:

<input
    id="textBox1"
    data-dojo-type="dijit.form.TextBox"
    value="some text here"/>
<button id="button1" data-dojo-type="dijit.form.Button">foo</button>

JavaScript:

require([
    "dojo/ready",
    "dijit/registry",
    "dijit/form/TextBox",
    "dijit/form/Button",
    "dojo/domReady!"
], function(
    ready,
    registry
) {
    ready(function() {
        var textBox = registry.byId("textBox1"),
            button = registry.byId("button1");        
        textBox.on("blur", function() {
            var start = this.textbox.selectionStart,
                end = this.textbox.selectionEnd;
            this.curStart = start;
            this.curEnd = end;
        });
        textBox.on("focus", function() {
            var cursorPosition = [this.curStart,this.curEnd];
            if(cursorPosition) {            
                this.textbox.setSelectionRange(cursorPosition[1], cursorPosition[1]);                                          
            }
        });
        button.on("click", function() {
            var cur = [textBox.curStart,textBox.curEnd];
         var val = textBox.get("value");
            var str = val.substring(0,cur[0])+ 'foo' + val.substring(cur[1]);
            textBox.set("value", str);
            textBox.focus();
            textBox.textbox.setSelectionRange(cur[0]+'foo'.length, cur[0]+'foo'.length);
        });

    });

});

这是小提琴链接:

http://jsfiddle.net/NE4Ev/6/

最新更新