js 实现简单特效
实现鼠标悬停变色效果
通过监听 mouseover 和 mouseout 事件动态修改元素背景色:
const box = document.getElementById('hoverBox');
box.addEventListener('mouseover', () => {
box.style.backgroundColor = '#ffcc00';
});
box.addEventListener('mouseout', () => {
box.style.backgroundColor = '#f0f0f0';
});
关键点:style 属性直接操作 CSS,适合快速修改简单样式。
点击元素放大动画
使用 transform 和 transition 实现平滑缩放效果:
const button = document.querySelector('.scaleButton');
button.addEventListener('click', () => {
button.style.transform = 'scale(1.2)';
setTimeout(() => {
button.style.transform = 'scale(1)';
}, 300);
});
优化建议:CSS 中预先添加 transition: transform 0.3s ease; 以提升动画流畅度。
滚动页面渐显元素
结合 window.scrollY 和透明度控制元素显示:
window.addEventListener('scroll', () => {
const element = document.querySelector('.fadeIn');
const position = element.getBoundingClientRect().top;
const screenHeight = window.innerHeight;
if (position < screenHeight * 0.75) {
element.style.opacity = '1';
element.style.transform = 'translateY(0)';
}
});
配套 CSS:
.fadeIn {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.5s, transform 0.5s;
}
实时输入字符计数
监听 input 事件统计文本框内容长度:
const textarea = document.getElementById('message');
const counter = document.getElementById('counter');
textarea.addEventListener('input', () => {
counter.textContent = `${textarea.value.length}/100`;
});
扩展功能:可通过 maxlength 属性限制输入长度。
简易图片轮播
通过修改 left 属性实现水平滑动效果:
let currentIndex = 0;
const slides = document.querySelectorAll('.slide');
function showSlide(index) {
slides.forEach((slide, i) => {
slide.style.left = `${100 * (i - index)}%`;
});
}
document.getElementById('next').addEventListener('click', () => {
currentIndex = (currentIndex + 1) % slides.length;
showSlide(currentIndex);
});
CSS 基础:需为 .slide 设置 position: absolute 和 width: 100%。

注意事项
- 性能优化:频繁触发的特效(如滚动事件)建议使用
requestAnimationFrame或防抖函数。 - 兼容性:现代浏览器支持上述 API,如需兼容旧版本可添加 polyfill。
- 扩展性:复杂特效建议使用 CSS 动画库(如 Animate.css)或 JavaScript 动画库(如 GSAP)。






