按钮点击动画
本课属于 Coddy HTML 学习旅程的“JavaScript 实战”单元。第 20 课,共 27 课。
有时,我们希望按钮在点击时立即给出反馈,比如缩小、发光或弹跳。我们可以使用 JavaScript 触发CSS 动画或过渡效果。
首先,在 HTML 中创建一个简单的按钮:
<button id="animatedButton">Click Me</button>然后,添加一些基础 CSS 来设置按钮样式:
#animatedButton {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: transform 0.2s, background-color 0.2s;
}现在,添加 JavaScript 来创建点击动画:
const button = document.getElementById('animatedButton');
button.addEventListener('click', function() {
// 添加一个类,实现点击效果
button.classList.add('button-clicked');
// 动画结束后移除这个类
setTimeout(function() {
button.classList.remove('button-clicked');
}, 200);
});最后,添加动画效果的 CSS:
.button-clicked {
transform: scale(0.95);
background-color: #45a049;
}点击后,按钮现在会稍微缩小并改变颜色,为用户提供视觉反馈。
挑战
简单点击按钮时,为它添加 CSS 类 "button-clicked",以提供视觉反馈。
在点击事件监听器中添加应用此类的代码行。
亲手试试
<!DOCTYPE html>
<html>
<head>
<title>Button Animation Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Interactive Button Demo</h1>
<p>Click the button below to see a smooth animation effect.</p>
</header>
<main class="content">
<button id="animatedButton" class="btn">Click Me</button>
</main>
<script src="script.js"></script>
</body>
</html>
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
JavaScript 实战中的所有课
自己练习: Web 在线编辑器