JavaScript 图片抖动是一种常见的网页动画效果,通过周期性地改变图片的位置,使其看起来像是在抖动。这种效果通常用于吸引用户的注意力或者增加页面的趣味性。
以下是一个简单的JavaScript实现图片抖动的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Shake Effect</title>
<style>
#shakyImage {
width: 200px;
height: 200px;
transition: all 0.1s ease-in-out;
}
</style>
</head>
<body>
<img id="shakyImage" src="path_to_your_image.jpg" alt="Shaky Image">
<script>
function shakeImage() {
const img = document.getElementById('shakyImage');
let x = 0;
let y = 0;
const shakeInterval = setInterval(() => {
img.style.transform = `translate(${x}px, ${y}px)`;
x = (x + (Math.random() - 0.5) * 10) % 10;
y = (y + (Math.random() - 0.5) * 10) % 10;
if (Math.random() > 0.9) clearInterval(shakeInterval);
}, 100);
}
window.onload = shakeImage;
</script>
</body>
</html>
问题:图片抖动效果过于剧烈,影响用户体验。
原因:抖动的幅度和频率设置得过高。
解决方法:
Math.random() - 0.5
中的系数,减小随机变化的范围。transition
的时间,使动画更加平滑。img.style.transform = `translate(${x}px, ${y}px)`;
x = (x + (Math.random() - 0.5) * 5) % 5; // 减小抖动幅度
y = (y + (Math.random() - 0.5) * 5) % 5;
通过这种方式,可以有效地控制抖动的剧烈程度,从而优化用户体验。
领取专属 10元无门槛券
手把手带您无忧上云