使用JS从输入框分别输入年、月、日,判断这一天是当年的第几天,区别闰年和平年.
时间: 2023-05-27 16:03:43 浏览: 56
以下是一个实现该功能的代码示例:
```js
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function getDayOfYear(year, month, day) {
const daysInMonth = [
31, // Jan
isLeapYear(year) ? 29 : 28, // Feb
31, // Mar
30, // Apr
31, // May
30, // Jun
31, // Jul
31, // Aug
30, // Sep
31, // Oct
30, // Nov
31, // Dec
];
let dayOfYear = 0;
for (let i = 0; i < month - 1; i++) {
dayOfYear += daysInMonth[i];
}
dayOfYear += day;
return dayOfYear;
}
const yearInput = document.querySelector('#year');
const monthInput = document.querySelector('#month');
const dayInput = document.querySelector('#day');
const resultDiv = document.querySelector('#result');
function handleSubmit() {
const year = parseInt(yearInput.value, 10);
const month = parseInt(monthInput.value, 10);
const day = parseInt(dayInput.value, 10);
const dayOfYear = getDayOfYear(year, month, day);
resultDiv.textContent = `这一天是第 ${dayOfYear} 天`;
}
document.querySelector('form').addEventListener('submit', (event) => {
event.preventDefault();
handleSubmit();
});
```
该代码包含两个函数。`isLeapYear` 函数用于检查给定的年份是否为闰年。`getDayOfYear` 函数接受年、月、日三个参数,返回这一天是当年的第几天。该函数结合了闰年和平年情况下每个月的天数。最后,使用表单元素和事件监听器来获取用户输入并渲染结果。
注意:该代码没有针对错误输入(如非整数、非法日期等)进行处理。实际应用中需要先进行输入合法性检查。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)