以下是一些常见的 JavaScript 炫酷特效代码示例及相关概念:
一、轮播图特效
概念:通过定时器控制图片的显示顺序,实现自动轮播效果。
优势:能有效地展示多张图片,吸引用户注意力。
类型:
应用场景:网站首页的图片展示、产品介绍页面。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.carousel {
width: 500px;
height: 300px;
overflow: hidden;
position: relative;
}
.carousel img {
width: 100%;
height: 100%;
position: absolute;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.carousel img.active {
opacity: 1;
}
</style>
</head>
<body>
<div class="carousel">
<img src="image1.jpg" alt="" class="active">
<img src="image2.jpg" alt="">
<img src="image3.jpg" alt="">
</div>
<script>
const images = document.querySelectorAll('.carousel img');
let index = 0;
function showNextImage() {
images[index].classList.remove('active');
index = (index + 1) % images.length;
images[index].classList.add('active');
}
setInterval(showNextImage, 2000);
</script>
</body>
</html>
二、鼠标悬停放大特效
概念:当鼠标悬停在元素上时,改变元素的尺寸。
优势:增强用户交互体验,突出重点元素。
类型:
应用场景:商品展示、按钮效果。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.box {
width: 100px;
height: 100px;
background-color: blue;
transition: transform 0.3s ease;
}
.box:hover {
transform: scale(1.2);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
三、粒子动画特效
概念:使用 JavaScript 和 Canvas 绘制大量的微小粒子,并通过计算它们的运动轨迹来创建动画效果。
优势:视觉效果震撼,能营造独特的氛围。
应用场景:网站背景、活动页面。
示例代码(较为复杂,仅作简单介绍):
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 - 1;
this.radius = Math.random() * 3;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
ctx.fill();
}
update() {
this.x += this.vx;
this.y += this.vy;
this.draw();
}
}
const particles = [];
for (let i = 0; i < 100; i++) {
particles.push(new Particle(Math.random() * canvas.width, Math.random() * canvas.height));
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => particle.update());
requestAnimationFrame(animate);
}
animate();
常见问题及解决方法:
领取专属 10元无门槛券
手把手带您无忧上云