持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第N天,点击查看活动详情、
前言
最近为了参与更文活动,也算是把我会的很多东西都已经写完了,所以最近有点不知道些什么。
但是为了我的全勤奖,今天就随便写一个“超级简单”的 Vue 版的 图片对比组件 吧。
简单分析
一般的滑动对比的组件,通常都是 横向滑动 或者 纵向滑动,这里就以横向滑动为例吧。
首先我们预想的效果图大致如下:
整个组件大致分为三个部分:左右两侧的图像预览,以及中间的提示线。
实现
首先,我们可以先定义 template 模板部分。
<template>
<div class="image-comparison" ref="box">
<div class="cover-image" ref="coverImage">
<img :src="images[0]" alt="" />
</div>
<div class="slider" ref="slider" @mousedown="startChange">
<span class="tag-icon"></span>
</div>
<img class="base-image" :src="images[1]" alt="" />
</div>
</template>
然后是样式部分:
.image-comparison {
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
* {
user-select: none;
}
.slider {
position: absolute;
left: calc(50% - 4px);
width: 8px;
height: 100%;
cursor: col-resize;
z-index: 20;
background: rgba(0, 0, 0, 0.5);
.tag-icon {
position: absolute;
top: 50%;
left: 50%;
border: 2px solid rgba(255, 255, 255, 0.5);
width: 40px;
height: 40px;
border-radius: 50%;
background: rgba(0, 0, 0, 0.5);
transform: translate(-50%, -50%);
}
}
.cover-image,
.base-image {
position: absolute;
left: 0;
height: 100%;
overflow: hidden;
}
.cover-image {
left: 0;
width: 50%;
z-index: 20;
}
img {
max-height: 100%;
}
}
这里的布局采用的是以下的设计方案:
- 外部的 父级 div 默认占满所有位置,开启相对定位模式,用来给后面的子元素定位
- 为了保证两个图片的尺寸和位置相对固定,且保留两个图片的位置起点在同一个点上,又要保证隐藏左边的图片时大小和位置不会变化,所以右侧的图片与 slider 元素的层级一致,左侧的图片通过放在一个 div 里面,并且这个div 和 外层父元素的高度一致。
- 设置图片的 max-height 属性为100%,确保图片过大时两个图片显示不一样;这里不能用max-width,因为左侧元素的父元素宽度是不确定的,如果以 width 为标准会造成图片缩小
事件
这里为了简单一点,只有鼠标按住中间的 slider 元素进行移动时,才会调整预览宽度,所以这里给中间的 slider 元素添加了mousedown 事件,然后添加了一个 全局的 mouseup 事件,保证鼠标抬起时直接移除相关事件。
在mousedown 触发之后注册鼠标移动事件,并且在 mouseup 触发后移除 mousemove 和 mouseup 的监听事件。
export default {
name: "ImageComparison",
props: {
images: {
type: Array,
default: () => []
}
},
data() {
return {
offsetX: 0
};
},
methods: {
startChange(event) {
this.offsetX = event.pageX - this.$refs.slider.offsetLeft;
window.addEventListener("mousemove", this.moveHandler);
window.addEventListener("mouseup", this.endChange);
},
endChange() {
window.removeEventListener("mousemove", this.moveHandler);
window.removeEventListener("mouseup", this.endChange);
},
moveHandler(e) {
this.$refs.slider.style.left = (e.pageX - this.offsetX - 4 || 0) + "px";
this.$refs.coverImage.style.width = (e.pageX - this.offsetX || 0) + "px";
}
}
};
最后
这里也只是实现了一个非常非常简单的图片滑动对比,后面其实也可以添加纵向滑动、滚轮滑动、通过配置化的鼠标按住滑动或者鼠标滑动直接更新滑动位置的功能。