在网页设计和开发中,JavaScript 是一种非常强大的工具,能够为网页增添丰富的视觉效果和交互体验。无论是简单的页面动画还是复杂的用户交互功能,JavaScript 都能轻松实现。下面是一些实用的 JavaScript 特效代码,帮助你快速提升网页的吸引力。
1. 简单的鼠标跟随效果
这是一个经典的鼠标跟随效果,可以让一个小球或图标随着鼠标的移动而移动。
```html
body {
margin: 0;
overflow: hidden;
}
.cursor {
position: absolute;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
pointer-events: none;
}
<script>
const cursor = document.querySelector('.cursor');
document.addEventListener('mousemove', e => {
cursor.style.left = e.pageX + 'px';
cursor.style.top = e.pageY + 'px';
});
</script>
```
2. 按钮点击波纹效果
按钮点击时产生波纹扩散的效果,可以增强用户的交互体验。
```html
button {
position: relative;
padding: 20px;
font-size: 16px;
color: white;
background-color: 007bff;
border: none;
border-radius: 5px;
cursor: pointer;
overflow: hidden;
transition: all 0.3s ease;
}
button::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0);
width: 20px;
height: 20px;
background-color: rgba(255, 255, 255, 0.5);
border-radius: 50%;
pointer-events: none;
transition: all 0.3s ease;
}
button:hover {
background-color: 0056b3;
}
button:active::after {
transform: translate(-50%, -50%) scale(1);
}
```
3. 页面加载进度条
在页面加载过程中显示一个进度条,让用户知道页面正在加载中。
```html
progress-bar {
position: fixed;
top: 0;
left: 0;
width: 0%;
height: 5px;
background-color: 007bff;
z-index: 9999;
}
<script>
window.addEventListener('load', () => {
const progressBar = document.getElementById('progress-bar');
let width = 0;
const interval = setInterval(() => {
if (width >= 100) {
clearInterval(interval);
} else {
width += 1;
progressBar.style.width = width + '%';
}
}, 10);
});
</script>
```
4. 图片懒加载
懒加载技术可以显著提高页面加载速度,尤其是在图片较多的情况下。
```html
img {
max-width: 100%;
height: auto;
display: block;
margin: 0 auto;
}
<script>
function lazyLoad() {
const images = document.querySelectorAll('img[data-src]');
images.forEach(img => {
if (img.getBoundingClientRect().top <= window.innerHeight && img.getBoundingClientRect().bottom >= 0) {
img.src = img.getAttribute('data-src');
img.removeAttribute('data-src');
}
});
}
window.addEventListener('scroll', lazyLoad);
window.addEventListener('load', lazyLoad);
</script>
```
这些 JavaScript 特效代码简单易用,可以帮助你在网页中添加一些动态效果,提升用户体验。希望对你有所帮助!