输入界面展示:
输出结果展示:
-
实现代码:
<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title></head><body><div><!-- 设计输入及点击界面 --><p>请输入您的出生日期(yyy/mm/dd):</p><input type="text" style="width: 60px;" id="year">/<input type="text" style="width: 60px;" id="month">/<input type="text" style="width: 60px;" id="day"></br><!-- 运用button标签并设置点击事件函数 --><button style="margin-top:10px " onclick="getAge()">计算</button></div><script>//计算周岁年龄的函数function getAge() {//定义返回值var returnAge//获取输入框参数var birthYear = document.getElementById("year").valuevar birthMonth = document.getElementById("month").valuevar birthDay = document.getElementById("day").value//获取当前时间d = new Date();var nowYear = d.getFullYear()var nowMonth = d.getMonth() + 1var 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)//结果弹窗显示}</script></body> </html>