返回更改输入的插入位置的逻辑

时间:2016-05-10 16:13:08

标签: javascript logic

我会感谢有关我应该如何为修改后的输入建立返回插入位置的逻辑的反馈。

案例:我们有一个输入,由JS处理,格式为x999y999z9999,其中x,y,z - 是我们根据具体情况定义的分隔符。我们按照预期处理和修改它,但是我似乎在逻辑上迷失了用于在可变长度的x,y和z的上下文中返回用户的插入位置。我甚至倾向于建立一个if \ else的整个复合体来响应那些长度波动,但可能有一个更简单的解决方案,我不知道。

提前致谢!

代码示例:https://jsfiddle.net/zktva4kc/

function doGetCaretPosition (field) {
 if (!!field){

	var CaretPos = 0;
	// IE Support
	if (document.selection) {

		field.focus ();
		var Sel = document.selection.createRange ();

		Sel.moveStart ('character', -field.value.length);

		CaretPos = Sel.text.length;
	}
	// Firefox support
	else if (field.selectionStart || field.selectionStart == '0')
		CaretPos = field.selectionStart;

	return (CaretPos);
 }else{
	console.log("No such field exist here for function initiation.");
 }
}


function setCaretPosition(field, pos)
{
 if (!!field){

	if(field.setSelectionRange)
	{
		field.focus();
		field.setSelectionRange(pos,pos);
	}
	else if (field.createTextRange) {
		var range = field.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
 }else{
	console.log("No such field exist here for function initiation.");
 }
}

function formatItDown(field, format) {  
 if (!!field){

    field.oninput = function () {
		var position=doGetCaretPosition(field);
		var sInput=this.value;
        var input = this.value;
        input = input.replace(/[^\d]/gi, "");

        var first = input.substr(0, 3);
        var second = input.substr(3, 3);
        var third = input.substr(6, 4);

        if (input.length > 3) {
            first = format[0] + first + format[1];
        }
        if (input.length > 6) {
            second = second + format[2];
			
        }

        formatted = first + second + third;
		//x012y456z8901
		/* this here is the problem area when we use some complex formats
		if ((formatted[3]!=sInput[3])&&(position>3)&&(position<6)){
			position=position+1;
		}else if ((formatted[7]!=sInput[7])&&(position>7)){
			position=position+1;
		}*/
		
        this.value = formatted;
		
		setCaretPosition(field, position);
    }
	

 }else{
	console.log("No such field exist here for function initiation.");
 }
}

formatItDown(document.getElementById('exampleInput'), ["--","==","__"]);
<input id='exampleInput'>

1 个答案:

答案 0 :(得分:0)

为什么不快速google以获得编码良好且无错误的内容?

这是我曾经使用过的好插件

https://github.com/acdvorak/jquery.caret