程序员的知识教程库

网站首页 > 教程分享 正文

教大家使用HTML代码实现年龄和星座计算

henian88 2025-03-05 16:17:54 教程分享 95 ℃ 0 评论



    
    年龄计算器
    


    

年龄 计算器


<script> // 初始化时设置最大可选日期为今日 window.onload = function() { const today = new Date().toISOString().split('T')[0]; document.getElementById('birthdate').setAttribute('max', today); }; // 星座计算函数 function getZodiacSign(date) { const month = date.getMonth() + 1; // 月份从0开始 const day = date.getDate(); if ((month === 1 && day >= 20) || (month === 2 && day <= 18 return if month='== 2' day>= 19) || (month === 3 && day <= 20 return if month='== 3' day>= 21) || (month === 4 && day <= 19 return if month='== 4' day>= 20) || (month === 5 && day <= 20 return if month='== 5' day>= 21) || (month === 6 && day <= 21 return if month='== 6' day>= 22) || (month === 7 && day <= 22 return if month='== 7' day>= 23) || (month === 8 && day <= 22 return if month='== 8' day>= 23) || (month === 9 && day <= 22 return if month='== 9' day>= 23) || (month === 10 && day <= 23 return if month='== 10' day>= 24) || (month === 11 && day <= 22 return if month='== 11' day>= 23) || (month === 12 && day <= 21 return if month='== 12' day>= 22) || (month === 1 && day <= 19)) return "摩羯座"; } function calculateAge() { const birthdate = document.getElementById('birthdate').value; if (!birthdate) { alert("请先选择出生日期"); return; } const birthDate = new Date(birthdate); const today = new Date(); // 年龄计算 let age = today.getFullYear() - birthDate.getFullYear(); const monthDiff = today.getMonth() - birthDate.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) { age--; } // 星座计算 const zodiac = getZodiacSign(birthDate); // 显示结果 const resultDiv = document.getElementById('result'); resultDiv.innerHTML = `
您的年龄是:${age} 岁
您的星座是:${zodiac}
生日:${birthDate.toLocaleDateString('zh-CN')}
`; } </script>

一、使用方法:

1.直接保存为.html文件用浏览器打开;

2.嵌入到任何网页的中;

二、运行结果展示:


运行结果展示

三、功能说明

1.日期选择器会自动禁用未来日期

2.支持12星座准确判断(包括跨月星座如摩羯座)

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表