本文实例为大家分享了js+html实现周岁年龄计算器的具体代码,供大家参考,具体内容如下
输入界面展示:
输出结果展示:
实现代码:
请输入您的出生日期(yyy/mm/dd):
/
/
计算
//计算周岁年龄的函数
function getAge() {
//定义返回值
var returnAge
//获取输入框参数
var birthYear = document.getElementById("year").value
var birthMonth = document.getElementById("month").value
var birthDay = document.getElementById("day").value
//获取当前时间
d = new Date();
var nowYear = d.getFullYear()
var nowMonth = d.getMonth() + 1
var nowDay = d.getDate()
//计算周岁年龄差
if (nowYear == birthYear) {
returnAge = 0; //同年 则为0岁
} else {
var ageDiff = nowYear - birthYear //年之差
if (ageDiff > 0) {
if (nowMonth == birthMonth) {
var dayDiff = nowDay - birthDay //日之差
if (dayDiff < 0) {
returnAge = ageDiff - 1
} else {
returnAge = ageDiff
}
} else {
var monthDiff = nowMonth - birthMonth //月之差
if (monthDiff < 0) {
returnAge = ageDiff - 1
} else {
returnAge = ageDiff
}
}
} else {
returnAge = -1 //输入有误
}
}
alert(returnAge)//结果弹窗显示
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程圈。