JS DOM实现鼠标滑动图片效果可以分为以下几个步骤:
首先,需要在HTML中编写需要实现滑动效果的图片。例如:
<div class="image-box">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
<img src="image4.jpg">
</div>
给图片盒子设置固定宽高,并将图片设置为绝对定位,重叠在一起。例如:
.image-box {
width: 400px;
height: 300px;
position: relative;
}
.image-box img {
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: .5s;
width: 100%;
height: 100%;
}
通过JS监听鼠标在图片盒子上的位置,然后根据位置计算出当前鼠标位置所对应的图片应该展示的透明度,并通过JS动态设置图片的透明度,实现滑动效果。例如:
const imageBox = document.querySelector('.image-box');
const images = imageBox.querySelectorAll('img');
const length = images.length;
imageBox.addEventListener('mousemove', event => {
const { x } = event;
images.forEach((image, index) => {
const opacity = (length - index) / length;
image.style.opacity = 1 - Math.abs(x - (index + 1) * imageBox.offsetWidth / length) / imageBox.offsetWidth * 2 + opacity;
});
});
以上是一个简单的实现鼠标滑动图片效果的方法。下面给出两个示例说明:
为了让图片滑动更加流畅,可以对代码进行优化,例如添加节流函数。以下是一个实现滑动效果并加入函数节流的示例代码:
function throttle(fn, delay) {
let lastTime = 0;
return function(...args) {
const nowTime = new Date().getTime();
if (nowTime - lastTime >= delay) {
fn.apply(this, args);
lastTime = nowTime;
}
}
}
const imageBox = document.querySelector('.image-box');
const images = imageBox.querySelectorAll('img');
const length = images.length;
const mousemoveHandler = throttle(function(event) {
const { x } = event;
images.forEach((image, index) => {
const opacity = (length - index) / length;
image.style.opacity = 1 - Math.abs(x - (index + 1) * imageBox.offsetWidth / length) / imageBox.offsetWidth * 2 + opacity;
});
}, 50);
imageBox.addEventListener('mousemove', mousemoveHandler);
除了鼠标滑动效果,还可以添加其他交互功能。例如,当鼠标移出图片盒子时,隐藏所有图片,只展示第一张图片。以下是一个实现鼠标移出时隐藏其他图片的示例代码:
function throttle(fn, delay) {
let lastTime = 0;
return function(...args) {
const nowTime = new Date().getTime();
if (nowTime - lastTime >= delay) {
fn.apply(this, args);
lastTime = nowTime;
}
}
}
const imageBox = document.querySelector('.image-box');
const images = imageBox.querySelectorAll('img');
const length = images.length;
const mousemoveHandler = throttle(function(event) {
const { x } = event;
images.forEach((image, index) => {
const opacity = (length - index) / length;
image.style.opacity = 1 - Math.abs(x - (index + 1) * imageBox.offsetWidth / length) / imageBox.offsetWidth * 2 + opacity;
});
}, 50);
const mouseleaveHandler = function() {
images.forEach((image, index) => {
image.style.opacity = index === 0 ? 1 : 0;
})
}
imageBox.addEventListener('mousemove', mousemoveHandler);
imageBox.addEventListener('mouseleave', mouseleaveHandler);