js实现在页面实时显示时间,一个按钮控制时间暂停和开始

该博客介绍了使用JS在HTML中实时显示时间,并通过一个按钮控制时间的暂停和开始,还给出了相应代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js实现在html实时显示时间,一个按钮控制时间暂停和开始.代码如下:

<head>
	<meta charset="UTF-8">
	<title></title>
</head>
<style>
	#main {
		width: 500px;
		height: 250px;
		margin: 20px auto;
		border: 1px solid #000000;
	}
	
	#the_button {
		width: 200px;
		margin: 10px auto;
	}
	
	label {
		display: inline-block;
		float: left;
		margin-right: 10px;
		width: 150px;
		text-align: right;
	}
</style>

<body>
	<div id="main">
		<label>当前的时间是:</label>
		<input type="text" id="text_1" readonly/><br />
		<div id="the_button">
			<input type="button" id="time_button" value="暂停" onclick="controlTime()" />
		</div>
	</div>
</body>
<script>
	/*
	 * 获取时间
	 */
	var myClock = setInterval("nowTime()",1000);
	function nowTime()
	{
		var date = new Date();
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var day = date.getDate();
		var hour = date.getHours();
		var min = date.getMinutes();
		var s = date.getSeconds();
		month = check(month);
		day = check(day);
		hour = check(hour);
		min = check(min);
		s = check(s);
		var timeStr = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + s; 
		document.getElementById("text_1").value = timeStr;
	}
	/*
	*添加0
	*/
	function check(i)
	{
		if( i < 10)
		{
			i = "0" + i;
		}
		return i;
	}
	/*
	*一个按钮实现开始和暂停功能
	*/
	function controlTime()
	{	
		var btnValue = document.getElementById("time_button").value;
		if(btnValue == "暂停")
		{
		 	window.clearInterval(myClock);
		 	document.getElementById("time_button").value = "开始";
		}
		if(btnValue == "开始")
		{
			window.setInterval("nowTime()",1000);
		 	document.getElementById("time_button").value = "暂停";
		}
	}
	
</script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值