开发者

Partially select text inside text field

I want my script to开发者_运维百科 select just a part of the text inside a text field (<input type="text"). How can I do this?


You will need to use Range, and cross-browser compatibility will probably be an issue.

Quirksmode: Creating a Range object from a Selection object

If jQuery is an option, here is a function you can use (reference)...

$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if(this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};


Check out Programmatically selecting partial text in an input field (may be a duplicate...)

Also, a helpful implementation concerning selected text and cursor position can be found here: http://javascript.nwbox.com/cursor_position/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜