htsign's blog

ノンジャンルで書くつもりだけど技術系が多いんじゃないかと思います

キャレット位置を指定するメソッドを作った

正直今更感がすごいけど、自分用メモとして。

HTMLTextAreaElement.prototype.setCaret =
HTMLInputElement.prototype.setCaret = function(pos){
    if (this.tagName.toLowerCase()==="input") {
        if (this.type!=="text" || this.type) return this;
    }
    var len = this.value.length;
    pos = pos && 0<=pos ? pos<=len ? pos<<0 : len : pos<<0;
    this.focus();
    if (this.setSelectionRange) { // DOM標準
        this.setSelectionRange(pos, pos);
    }
    else if (this.createTextRange) { // IE用
        var tr = this.createTextRange();
        tr.move("character", pos);
        tr.select();
    }
    return this;
};

<input><input type="text"><textarea>のときに有効で、

Element.setCaret(num);

ってな感じで使う。
numがキャレットの位置。開始が0。
たぶん何を入れても例外は起きないと思う。テストしてないけど。

使う場面は多くなさそう。