我需要像xxxx-xxx-xxx使用 JavaScript 一样格式化我的电话号码,我该如何制作呢?下面是代码:超文本标记语言<input onkeypress="isInputNumber(event)" type="text" id="phonenumber" placeholder = "xxxx-xxx-xxxx" maxlength="11"/>JavaScriptfunction isInputNumber(evt){ var ch=String.fromCharCode(evt.which); if(!(/[0-9]/.test(ch))){ evt.preventDefault(); }}
1 回答
哆啦的时光机
TA贡献1779条经验 获得超6个赞
document.getElementById('phonenumber').addEventListener('blur', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{4})(\d{3})(\d{4})/);
e.target.value = x[1] + '-' + x[2] + '-' + x[3];
});
function isInputNumber(evt){
var ch=String.fromCharCode(evt.which);
if(!(/[0-9]/.test(ch))){
evt.preventDefault();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input onkeypress="isInputNumber(event)" type="text" id="phonenumber" placeholder = "xxxx-xxx-xxxx" maxlength="11"/>
- 1 回答
- 0 关注
- 110 浏览
添加回答
举报
0/150
提交
取消