在前端开发中,通过JavaScript和CSS实现鼠标动作控制图片纵向滚动是一种常见的交互效果。这种效果通常用于创建动态的用户界面,增强用户体验。
以下是一个简单的示例,展示如何通过鼠标悬停控制图片纵向滚动:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mouse Hover Scroll</title>
<style>
.container {
width: 300px;
height: 200px;
overflow: hidden;
position: relative;
}
.image-container {
position: absolute;
top: 0;
left: 0;
transition: top 0.5s ease-in-out;
}
img {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<div class="container">
<div class="image-container" id="imageContainer">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
</div>
<script>
const container = document.querySelector('.container');
const imageContainer = document.getElementById('imageContainer');
const images = imageContainer.querySelectorAll('img');
let currentIndex = 0;
container.addEventListener('mouseenter', () => {
setInterval(() => {
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
imageContainer.style.top = '0';
}
imageContainer.style.top = `-${currentIndex * 200}px`;
}, 2000);
});
container.addEventListener('mouseleave', () => {
clearInterval();
imageContainer.style.top = '0';
});
</script>
</body>
</html>
通过以上方法,可以有效地实现和控制鼠标动作控制图片纵向滚动的效果。
领取专属 10元无门槛券
手把手带您无忧上云