通过用户输入出生年月日,来判断用户的星座,给出一个结论 将功能开发成为一个独立的js文件,并通过html页面加载,运行。
时间: 2023-05-24 21:04:24 浏览: 184
根据出生日期判断你的星座.rar
以下是一个实现此功能的独立的JavaScript文件,文件名为"zodiac.js":
```
// 判断星座的函数,接受参数month和day
function getZodiac(month, day) {
var zodiacs = [
{ name: "摩羯座", startMonth: 1, startDate: 1, endMonth: 1, endDate: 19 },
{ name: "水瓶座", startMonth: 1, startDate: 20, endMonth: 2, endDate: 18 },
{ name: "双鱼座", startMonth: 2, startDate: 19, endMonth: 3, endDate: 20 },
{ name: "白羊座", startMonth: 3, startDate: 21, endMonth: 4, endDate: 19 },
{ name: "金牛座", startMonth: 4, startDate: 20, endMonth: 5, endDate: 20 },
{ name: "双子座", startMonth: 5, startDate: 21, endMonth: 6, endDate: 20 },
{ name: "巨蟹座", startMonth: 6, startDate: 21, endMonth: 7, endDate: 22 },
{ name: "狮子座", startMonth: 7, startDate: 23, endMonth: 8, endDate: 22 },
{ name: "处女座", startMonth: 8, startDate: 23, endMonth: 9, endDate: 22 },
{ name: "天秤座", startMonth: 9, startDate: 23, endMonth: 10, endDate: 22 },
{ name: "天蝎座", startMonth: 10, startDate: 23, endMonth: 11, endDate: 21 },
{ name: "射手座", startMonth: 11, startDate: 22, endMonth: 12, endDate: 21 },
{ name: "摩羯座", startMonth: 12, startDate: 22, endMonth: 12, endDate: 31 }
];
// 循环比较每个星座的开始日期和结束日期
for (var i = 0; i < zodiacs.length; i++) {
var zodiac = zodiacs[i];
if (
(month === zodiac.startMonth && day >= zodiac.startDate) ||
(month === zodiac.endMonth && day <= zodiac.endDate)
) {
return zodiac.name; // 返回匹配到的星座名称
}
}
return undefined; // 未匹配到返回undefined
}
// 获取用户输入的年月日,并调用getZodiac函数获取星座
function calculateZodiac() {
var year = parseInt(prompt("请输入出生年份:", ""));
var month = parseInt(prompt("请输入出生月份:", ""));
var day = parseInt(prompt("请输入出生日期:", ""));
if (isNaN(year) || isNaN(month) || isNaN(day)) {
alert("请正确输入出生年月日!");
} else {
var zodiac = getZodiac(month, day);
if (zodiac) {
alert(year + "年" + month + "月" + day + "日的星座是:" + zodiac);
} else {
alert("无法匹配到您的星座信息,请检查输入是否正确。");
}
}
}
```
在HTML页面中,可以通过以下方式引入上述JavaScript文件:
```
<html>
<head>
<meta charset="UTF-8">
<title>判断星座</title>
<script src="zodiac.js"></script>
</head>
<body>
<button onclick="calculateZodiac()">点击获取星座</button>
</body>
</html>
```
以上代码演示了在页面中添加一个按钮,当用户点击该按钮时,会弹出输入框让用户输入出生年月日信息,并根据输入结果判断用户的星座,并弹出结果提示框。
阅读全文