本文实例为大家分享了js+html实现周岁年龄计算器的具体代码,供大家参考,具体内容如下
输入界面展示:
输出结果展示:
实现代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div> <!-- 设计输入及点击界面 --> <p>请输入您的出生日期(yyy/mmhttps://img.qb5200.com/download-x/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").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)//结果弹窗显示 } </script> </body> </html>