1、html代码
<div class="box">
请输入身份证号码:<input type="text" name="" id="sex" />
</div>
2、css代码
* {
margin: 0;
padding: 0;
}
.box {
display: flex;
justify-content: center;
margin-top: 100px;
}
3、js代码
/**
* 按身份证号码获取性别
* @idNumber 身份证号码
* @return 男 女 身份证格式输入有误!
*/
function getGender(idNumber) {
let res = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
if (idNumber && res.test(idNumber)) {
let genderCode = idNumber.charAt(16);
if (parseInt(genderCode) % 2 == 0) {
return '女';
}
return '男';
} else {
return '身份证格式输入有误!';
}
}
// 获取身份证号码
let id = document.querySelector('#sex');
// 输入框失焦后获取手机号
id.onblur = function(){
if(id.value) {
let sex = getGender(id.value);
console.log(sex);
}
}
以上便是通过身份证号码判断性别的方式