一、需求
1、 点击左箭头,导航栏向左滑动。当导航栏滑动到最左边时,隐藏右箭头;
2、 点击右箭头,导航栏向右滑动。当导航栏滑动到最右边时,隐藏左箭头;
3、点击导航A,导航A高亮显示。
二、思路
1、 滑动效果:导航栏使用margin-left属性,实现左右滑动效果
distance变量,保存滑动距离。左滑 ,distance - 导航宽度;向右滑,distance + 导航宽度
2、隐藏/显示左箭头(<)
(1) 滚动区域 - 隐藏区域 < 可视区域。
true,说明右侧导航已全部显示,隐藏左箭头
false,说明右侧导航未全部显示,显示左箭头
(2) 滚动区域 <= 可视区域,隐藏左箭头;反之,显示左箭头
3、 隐藏/显示右箭头(>)
(1) 导航栏未发生移动时,则隐藏右箭头;反之,显示右箭头
(2) 第一次加载页面时,无论什么情况下,右侧(>)箭头都是隐藏状态
三、图示
四、代码
<template>
<div class="scroll">
<span class="arrow-style" v-show="showLeft" @click="moveMethod('left')"
><</span
>
<div class="scroll-main" ref="scrollMain">
<div
class="scroll-main-wrap"
ref="wrap"
:style="{ 'margin-left': distance + 'px' }"
>
<div
v-for="(item, index) in 30"
:key="item"
:ref="'nav' + item"
class="wrap-detail"
:class="index === currentIndex && 'click-style'"
@click="changeIndex(index)"
>
导航{{ item < 10 ? "0" + item : item }}
</div>
</div>
</div>
<span class="arrow-style" v-show="showRight" @click="moveMethod('right')"
>></span
>
</div>
</template>
<script>
export default {
name: "scroll",
data() {
return {
currentIndex: 0,
distance: 0,
scollWith: 0,
wrapWith: 0,
navWidth: 0,
showLeft: true,
showRight: false,
};
},
mounted() {
// 初始化
this.scollWith = this.$refs.scrollMain.offsetWidth;
this.wrapWith = this.$refs.wrap.offsetWidth;
this.navWidth =
document.getElementsByClassName("wrap-detail")[0].offsetWidth;
this.wrapWith <= this.scollWith && (this.showLeft = false);
// 监听屏幕尺寸
window.onresize = () => {
this.scollWith = this.$refs.scrollMain.clientWidth;
this.convertArrow();
};
},
methods: {
changeIndex(index) {
this.currentIndex = index;
},
moveMethod(flag) {
// 移动
this.distance += flag === "left" ? -91 : 91;
this.convertArrow();
},
convertArrow() {
/**
* 左箭头:滚动区域 - 隐藏区域 < 可视区域
* true:隐藏左箭头(右侧导航已全显示)
* false:显示左箭头(右侧导航未全显示)
*/
let rollWidth = this.wrapWith - Math.abs(this.distance);
this.showLeft = rollWidth < this.scollWith ? false : true;
// 右箭头
this.showRight = this.distance == 0 ? false : true;
},
},
};
</script>
<style lang="scss" scoped>
body {
margin: 0;
padding: 0;
}
.scroll {
width: 100vw;
height: 50px;
line-height: 50px;
background: gray;
.arrow-style {
color: #fff;
padding: 0 20px;
cursor: pointer;
}
.scroll-main {
display: inline-block;
width: calc(100vw - 104px);
overflow: hidden;
vertical-align: bottom;
.scroll-main-wrap {
width: max-content;
.wrap-detail {
color: #fff;
float: left;
padding: 0 20px;
cursor: pointer;
border-left: 1px solid #fff;
}
.wrap-detail:last-child {
border-right: 1px solid #fff;
}
.click-style {
background: yellowgreen;
}
}
.scroll-main-wrap:after {
content: "";
display: block;
clear: both;
}
}
}
</style>
五、效果
滑动导航栏