how to move the text in input using js

2020-03-31 05:21发布

问题:

I just use js to set an text input's value. But when the text is longer than input can hold, the excess text is hidden in the right part of the input. How can I hide the excess text in left area just like the normal typing? Forgive my poor english.

回答1:

When you perform this your caret position is at the beginning of the text. You need to move the caret position to the end.

function setCursor(node,pos){
    var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;

    if (!node) {
        return false;
    } else if (node.createTextRange) {
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    } else if (node.setSelectionRange) {
        node.setSelectionRange(pos,pos);
        return true;
    }
    return false;
}

setCursor(input, input.value.length); // input is your textbox