目录
效果图
把之前完成的一个效果图摘出来记录一下,核心代码在这里,如果项目中用到其他的技术,也很容易改。
需求分析
- 展示数据
始终一行
,多余的部分可以出滚动条,同时隐藏滚动条样式。 - 支持笔记本
触控滑动
展示 - 支持
鼠标点击滑动
,多余的时候出现箭头按钮,默认滑动3个卡片的位置,顶头就切换方向 - 当
页面出现变动的时候要监听
及时显示或隐藏按钮
实现分析
样式展示分析
- 外层控制总体组件宽度
- 内层箭头区域展示,内部使用flex布局,绝对定位到右侧
- 内部箭头svg图标,垂直居中
- 内层控制滚动区域宽度,内部使用flex布局,控制一层展示,溢出滚动展示,并隐藏滚动条
- 内部确定卡片宽高和间距,最后一个右边距为0
- 内层箭头区域展示,内部使用flex布局,绝对定位到右侧
变量分析
- 卡片
list:Array
- 控制箭头显隐
arrowShow:Boolean
,控制箭头方向direction:String
- 获取滚动位置
scrollPosition = {left: 0, top: 0}
- 计算宽度需要的ref:控制滚动条层
groupBoxRef
,卡片groupCardRef
方法分析
- 获取list(可以http,也可以props,根据需求来定)
- 页面挂载之后,监听groupBoxRef的scroll事件和窗口变化的resize事件
- 箭头的显隐判断方法,改变箭头方向的方法
- 鼠标点击箭头的方法
实现步骤
1. 实现模板
<template>
<div class="index-group-box">
<!-- 右边滑动箭头 -->
<div class="scrollX">
<img src='../assets/arrow-left-bold.svg'/>
</div>
<!-- 卡⽚ -->
<div class="index-group-boxIn" ref="groupBoxRef">
<div
v-for="item in groupInfo"
:key="item.id"
ref="groupCardRef"
class="group-card"
>
<div class="card-name">
名称
<span>{
{
item.name }}</span>
</div>
</div>
</div>
</div>
</template>
2. 实现css
<style scoped>
.index-group-box {
padding-right: 16px;
position: relative;
box-sizing: border-box;
width: 100%;
}
.scrollX {
width: 16px;
position: absolute;
top: 0;
right: 0;
height: 100%;
background-color: #512D6D;
display: flex;
justify-content: center;
align-items: center
}
.scrollX:hover {
cursor: pointer;
background-color: #65447d;
}
.index-group-boxIn {
display: flex;
scroll-behavior: smooth;
white-space: nowrap;
overflow-x: auto;
flex: none;
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE 10+ */
}
.index-group-boxIn::-webkit-scrollbar {
display: none; /* Chrome Safari */
}
.group-card {
padding: 8px 16px;
box-sizing:border-box;
width: 200px;
height: 100px;
border-radius: 4px;
margin-right: 16px;
flex: none;
background: #71EFA3;
color: #54436B;
}
.group-card span{
color: #54436B;
}
.group-card:hover{
background: #ACFFAD;
}
.group-card:nth-last-of-type(1){
margin-right: 0px;
}
</style>
3. 首先获取list
<script>
import {
defineComponent, ref } from 'vue';
export default defineComponent({
name: 'scroll'