js 实现简单特效
实现鼠标悬停按钮变色
通过监听鼠标事件改变按钮背景色,适合增强交互体验。以下代码使用纯JavaScript实现:
const button = document.getElementById('hoverButton');
button.addEventListener('mouseover', () => {
button.style.backgroundColor = '#ff5722';
button.style.transition = 'background-color 0.3s ease';
});
button.addEventListener('mouseout', () => {
button.style.backgroundColor = '#4CAF50';
});
创建元素淡入效果
使用CSS配合JavaScript实现平滑的淡入动画效果:
function fadeIn(element) {
element.style.opacity = 0;
element.style.display = 'block';
let opacity = 0;
const timer = setInterval(() => {
opacity += 0.1;
element.style.opacity = opacity;
if (opacity >= 1) clearInterval(timer);
}, 50);
}
// 调用示例:fadeIn(document.getElementById('target'));
实现滚动动画特效
监听滚动事件创建视差效果或元素显示动画:
window.addEventListener('scroll', () => {
const elements = document.querySelectorAll('.animate-on-scroll');
elements.forEach(el => {
const rect = el.getBoundingClientRect();
if (rect.top < window.innerHeight * 0.75) {
el.classList.add('active');
}
});
});
需配合CSS:
.animate-on-scroll {
opacity: 0;
transform: translateY(20px);
transition: all 0.6s ease;
}
.animate-on-scroll.active {
opacity: 1;
transform: translateY(0);
}
制作点击波纹效果
模拟Material Design的点击波纹动画:
function createRipple(event) {
const button = event.currentTarget;
const circle = document.createElement('span');
const diameter = Math.max(button.clientWidth, button.clientHeight);
const radius = diameter / 2;
circle.style.width = circle.style.height = `${diameter}px`;
circle.style.left = `${event.clientX - button.offsetLeft - radius}px`;
circle.style.top = `${event.clientY - button.offsetTop - radius}px`;
circle.classList.add('ripple');
const ripple = button.getElementsByClassName('ripple')[0];
if (ripple) ripple.remove();
button.appendChild(circle);
}
// 为元素添加点击事件:element.addEventListener('click', createRipple);
需配套CSS:
.ripple {
position: absolute;
border-radius: 50%;
background-color: rgba(255,255,255,0.7);
transform: scale(0);
animation: ripple 0.6s linear;
pointer-events: none;
}
@keyframes ripple {
to {
transform: scale(4);
opacity: 0;
}
}
实现打字机效果
模拟逐字打印的文字动画:
function typeWriter(element, text, speed = 100) {
let i = 0;
element.textContent = '';
function typing() {
if (i < text.length) {
element.textContent += text.charAt(i);
i++;
setTimeout(typing, speed);
}
}
typing();
}
// 使用示例:typeWriter(document.getElementById('typeElement'), 'Hello World!');






