关闭

实现苹果手机号码编辑效果

171人阅读 评论(0) 收藏 举报

原本是用jquery写的,这里只有关键代码,没写id为phone的输入框

$("#phone").on("keyup", function(e) {//用电脑shift加方向无法选取文本,手机上无此操作,不管了。粘贴后焦点位置不对

var cursortPosition = getCursortPosition(this);
var phone = decrPhone(this.value);
//var selectText = getSelectText();
/*if(selectText){//有选中内容时

}*/
//if(e.keyCode < 48)//输入非字符
// cursortPosition--;
if (phone.length >= 9) {


this.value = encrPhone(phone);
if (phone.length == 9) {
if (e.keyCode == 8 || cursortPosition < 3)
setCaretPosition(this, cursortPosition);
else if (cursortPosition < 8)
setCaretPosition(this, cursortPosition + 1);
else
setCaretPosition(this, cursortPosition + 2);
} else
setCaretPosition(this, cursortPosition);
} else {
this.value = phone;
if (phone.length == 8) {
if (e.keyCode != 8 || cursortPosition < 4)
setCaretPosition(this, cursortPosition);
else if (cursortPosition < 9)
setCaretPosition(this, cursortPosition - 1);
else
setCaretPosition(this, cursortPosition - 2);
} else
setCaretPosition(this, cursortPosition);
}
});


/**获取真实号码*/
function decrPhone(phone) {
return phone.replace(/-+/g, "");
}
/**加密号码*/
function encrPhone(phone) {
var newPhone = "";
if (phone.length >= 9) {
for ( var i = 0; i < phone.length; i++) {
newPhone += phone[i];
if (i == 2 || i == 6) {
newPhone += "-";
}
}
return newPhone;
} else {
return phone;
}
}


/*$(function() {
 $("#txt").click(function() {
 var position = 0;
 var txtFocus = document.getElementById("txt");
 if ($.browser.msie) {
 var range = txtFocus.createTextRange();
 range.move("character", position);
 range.select();
 }
 else {
 //obj.setSelectionRange(startPosition, endPosition);
 txtFocus.setSelectionRange(position, position);
 txtFocus.focus();
 }
 });
 });*/
//1.获取光标位置
function getCursortPosition(ctrl) {// 获取光标位置函数
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
} // Firefox
// support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
//2.设置光标位置
function setCaretPosition(ctrl, pos) {// 设置光标位置函数
if (ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(pos, pos);
} else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
//获取文本框选中值
function getSelectText() {
var content;
if (document.all) {
content = document.selection.createRange();
} else {
content = window.getSelection();
content.text = content.toString();
}
var str = content.text;// 选择的内容
return str;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6237次
    • 积分:141
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条
    文章分类