JavaScript编写代码实现上滑,下滑,淡出,淡入,隐藏,显示图片功能
时间: 2024-02-28 15:57:58 浏览: 93
好的,以下是 JavaScript 代码示例,用于实现上滑、下滑、淡出、淡入、隐藏和显示图片功能。
```javascript
class ImageSlider {
constructor(imagePath) {
this.image = new Image();
this.image.src = imagePath;
this.imgElement = document.createElement('img');
this.imgElement.src = imagePath;
document.body.appendChild(this.imgElement);
}
slideUp(distance, duration) {
const startY = this.imgElement.offsetTop;
const endY = startY - distance;
const startTime = new Date().getTime();
const slide = () => {
const elapsed = new Date().getTime() - startTime;
const progress = elapsed / duration;
if (progress > 1) {
this.imgElement.style.top = `${endY}px`;
return;
}
const newY = startY + ((endY - startY) * progress);
this.imgElement.style.top = `${newY}px`;
window.requestAnimationFrame(slide);
};
window.requestAnimationFrame(slide);
}
slideDown(distance, duration) {
const startY = this.imgElement.offsetTop;
const endY = startY + distance;
const startTime = new Date().getTime();
const slide = () => {
const elapsed = new Date().getTime() - startTime;
const progress = elapsed / duration;
if (progress > 1) {
this.imgElement.style.top = `${endY}px`;
return;
}
const newY = startY + ((endY - startY) * progress);
this.imgElement.style.top = `${newY}px`;
window.requestAnimationFrame(slide);
};
window.requestAnimationFrame(slide);
}
fadeIn(steps, duration) {
const alphaStep = 1 / steps;
let alpha = 0;
let currentStep = 0;
const fade = () => {
alpha += alphaStep;
currentStep++;
this.imgElement.style.opacity = alpha;
if (currentStep < steps) {
window.requestAnimationFrame(fade);
}
};
window.requestAnimationFrame(fade);
}
fadeOut(steps, duration) {
const alphaStep = 1 / steps;
let alpha = 1;
let currentStep = 0;
const fade = () => {
alpha -= alphaStep;
currentStep++;
this.imgElement.style.opacity = alpha;
if (currentStep < steps) {
window.requestAnimationFrame(fade);
}
};
window.requestAnimationFrame(fade);
}
hide() {
this.imgElement.style.display = 'none';
}
show() {
this.imgElement.style.display = 'block';
}
}
const slider = new ImageSlider('image.jpg');
slider.slideUp(100, 1000);
slider.fadeOut(30, 1000);
slider.hide();
slider.show();
slider.fadeIn(30, 1000);
slider.slideDown(100, 1000);
```
以上代码创建了一个名为 ImageSlider 的类,它包含了一个 img 元素,该元素用于显示图像。我们可以在此类中实现上滑、下滑、淡出、淡入、隐藏和显示图片功能。例如,我们可以使用 slideUp() 和 slideDown() 方法来实现上滑和下滑,使用 fadeIn() 和 fadeOut() 方法来实现淡入和淡出,使用 hide() 和 show() 方法来实现隐藏和显示。
请注意,以上代码示例中的方法仅适用于单个图像。如果您需要处理多个图像,请使用列表或其他数据结构来存储它们。
阅读全文