应用要求: 通过用户输入出生年月日,来判断用户的星座,给出一个结论 提示: 将功能开发成为一个独立的js文件,并通过html页面加载,运行。
时间: 2023-05-23 14:07:34 浏览: 108
根据出生日期判断你的星座.rar
A:
可以使用以下代码实现:
```javascript
function getConstellation(dateStr) {
var date = new Date(dateStr);
var month = date.getMonth() + 1;
var day = date.getDate();
var constellation = '';
switch(month) {
case 1:
if(day <= 19) {
constellation = '魔羯座';
} else {
constellation = '水瓶座';
}
break;
case 2:
if(day <= 18) {
constellation = '水瓶座';
} else {
constellation = '双鱼座';
}
break;
case 3:
if(day <= 20) {
constellation = '双鱼座';
} else {
constellation = '白羊座';
}
break;
case 4:
if(day <= 19) {
constellation = '白羊座';
} else {
constellation = '金牛座';
}
break;
case 5:
if(day <= 20) {
constellation = '金牛座';
} else {
constellation = '双子座';
}
break;
case 6:
if(day <= 21) {
constellation = '双子座';
} else {
constellation = '巨蟹座';
}
break;
case 7:
if(day <= 22) {
constellation = '巨蟹座';
} else {
constellation = '狮子座';
}
break;
case 8:
if(day <= 22) {
constellation = '狮子座';
} else {
constellation = '处女座';
}
break;
case 9:
if(day <= 22) {
constellation = '处女座';
} else {
constellation = '天秤座';
}
break;
case 10:
if(day <= 23) {
constellation = '天秤座';
} else {
constellation = '天蝎座';
}
break;
case 11:
if(day <= 22) {
constellation = '天蝎座';
} else {
constellation = '射手座';
}
break;
case 12:
if(day <= 21) {
constellation = '射手座';
} else {
constellation = '魔羯座';
}
break;
}
return constellation;
}
```
将以上代码保存为一个独立的JS文件,在HTML页面中加载,输入出生年月日,调用函数即可:
```html
<html>
<head>
<script src="constellation.js"></script>
</head>
<body>
<input type="date" id="birthday">
<button onclick="showConstellation()">确定</button>
<div id="result"></div>
</body>
<script>
function showConstellation() {
var birthday = document.getElementById("birthday").value;
var constellation = getConstellation(birthday);
var resultDiv = document.getElementById("result");
resultDiv.innerHTML = "您的星座为:" + constellation;
}
</script>
</html>
```
阅读全文