js实现按钮效果
实现基础按钮效果
使用HTML和CSS创建基础按钮样式,通过JavaScript添加交互效果:
<button id="myButton">点击我</button>
#myButton {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
#myButton:hover {
background-color: #45a049;
}
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
this.textContent = '已点击!';
this.style.backgroundColor = '#ff9800';
});
添加点击动画效果
使用CSS动画和JavaScript触发:
@keyframes bounce {
0%, 100% { transform: scale(1); }
50% { transform: scale(0.9); }
}
.animate {
animation: bounce 0.3s;
}
button.addEventListener('click', function() {
this.classList.add('animate');
setTimeout(() => this.classList.remove('animate'), 300);
});
实现按钮禁用状态
通过JavaScript控制按钮状态:
button.addEventListener('click', function() {
this.disabled = true;
this.textContent = '处理中...';
// 模拟异步操作
setTimeout(() => {
this.disabled = false;
this.textContent = '完成!';
}, 2000);
});
创建波纹点击效果
添加视觉反馈的波纹动画:
.ripple {
position: relative;
overflow: hidden;
}
.ripple-effect {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.7);
transform: scale(0);
animation: ripple 0.6s linear;
}
@keyframes ripple {
to {
transform: scale(4);
opacity: 0;
}
}
button.addEventListener('click', function(e) {
const ripple = document.createElement('span');
ripple.classList.add('ripple-effect');
const rect = this.getBoundingClientRect();
const size = Math.max(rect.width, rect.height);
ripple.style.width = ripple.style.height = `${size}px`;
ripple.style.left = `${e.clientX - rect.left - size/2}px`;
ripple.style.top = `${e.clientY - rect.top - size/2}px`;
this.appendChild(ripple);
setTimeout(() => ripple.remove(), 600);
});
实现按钮加载状态
创建加载动画指示器:

.loading::after {
content: "";
display: inline-block;
width: 16px;
height: 16px;
margin-left: 8px;
border: 2px solid #fff;
border-radius: 50%;
border-color: #fff transparent #fff transparent;
animation: loading 1.2s linear infinite;
}
@keyframes loading {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
button.addEventListener('click', function() {
this.classList.add('loading');
this.disabled = true;
setTimeout(() => {
this.classList.remove('loading');
this.disabled = false;
}, 3000);
});






