<!DOCTYPE html>
<html lang=”zh-CN”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>日期切换示例</title>
<style>
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial; line-height: 1.6; padding: 20px; }
#btn { cursor: pointer; padding: 6px 12px; }
</style>
</head>
<body>
<p id=”text”>点击按钮显示日期</p>
<button id=”btn”>显示日期</button>
<script>
// 1) 绑定节点
const textEl = document.getElementById(‘text’);
const btnEl = document.getElementById(‘btn’);
// 2) 保存原文字,并用布尔变量记录当前是否为“原文字”状态
const originalText = textEl.textContent;
let isOriginal = true;
// 3) 点击切换
btnEl.addEventListener(‘click’, () => {
if (isOriginal) {
const now = new Date();
// 显示本地格式的日期时间(含时分秒)
textEl.textContent = now.toLocaleString();
btnEl.textContent = ‘恢复原文’;
} else {
textEl.textContent = originalText;
btnEl.textContent = ‘显示日期’;
}
// 4) 翻转状态
isOriginal = !isOriginal;
});
</script>
</body>
</html>


没有回复内容