用js在文本框中显示当前时间
时间: 2023-10-12 18:09:05 浏览: 58
您可以使用 JavaScript 中的 Date 对象来获取当前时间,并将其显示在文本框中。以下是一个示例代码:
```html
<input type="text" id="time">
<script>
// 获取当前时间
var currentTime = new Date();
// 将时间格式化为字符串
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var timeString = hours + ':' + minutes + ':' + seconds;
// 将时间字符串显示在文本框中
document.getElementById('time').value = timeString;
</script>
```
此代码将创建一个文本框,并在文本框中显示当前的时间(格式为 hh:mm:ss)。
相关问题
web点击按钮在文本框中显示自动走动的时间代码
你需要使用JavaScript来实现这个功能。你可以在HTML中添加一个按钮和一个文本框,然后在JavaScript中编写代码来实现。
以下是一个例子:
HTML代码:
```
<button onclick="showTime()">显示时间</button>
<input type="text" id="time">
```
JavaScript代码:
```
function showTime() {
var time = new Date();
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
// 将小时转换为12小时制
hours = hours % 12;
hours = hours ? hours : 12;
// 添加前导零
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
// 将时间显示在文本框中
document.getElementById('time').value = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
// 每秒钟更新一次时间
setTimeout(showTime, 1000);
}
```
在这个例子中,`showTime()` 函数会获取当前时间,并将其显示在文本框中。然后,使用 `setTimeout()` 函数每秒钟更新一次时间。当用户点击按钮时,`showTime()` 函数会被调用。
web点击按钮在文本框中显示自动走动的时间和日期
你可以使用JavaScript来实现这个功能。以下是一个示例代码:
HTML代码:
```
<input type="text" id="datetime" size="40"/>
<button onclick="showDateTime()">显示时间和日期</button>
```
JavaScript代码:
```
function showDateTime() {
var datetime = new Date();
document.getElementById('datetime').value = datetime.toLocaleString();
setTimeout(showDateTime, 1000); //每秒更新一次时间和日期
}
```
当用户点击按钮时,`showDateTime()`函数将被调用。这个函数使用JavaScript的`Date()`对象来获取当前时间和日期,并将其显示在文本框中。`setTimeout()`函数用于每秒更新一次时间和日期。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![html](https://img-home.csdnimg.cn/images/20210720083451.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)