0

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

我想要完全一样的东西:http: //jsfiddle.net/NE4Ev/6/ 但这在 Internet Explorer 中不起作用。有人可以帮忙吗?

4

2 回答 2

2

监听 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/

于 2012-05-30T10:42:39.763 回答
1

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

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

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/

于 2012-05-30T12:05:47.187 回答