如何使用js在输入中移动文本 [英] how to move the text in input using js

查看:70
本文介绍了如何使用js在输入中移动文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是使用js来设置文本输入的值。但是当文本长于输入可以保持时,多余的文本隐藏在输入的右侧部分。如何像正常打字一样隐藏左侧区域中的多余文本?
原谅我的英语不好。

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.

推荐答案

执行此操作时,您的插入位置位于文本的开头。您需要将插入位置移动到最后。

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

这篇关于如何使用js在输入中移动文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆