做app的伙伴都会知道,好多二级标题横向排列,数量多的话有时候就要做出滑动的处理,但是点击后边超出隐藏的标题时,就需要自己滑动到最后,非常不利于用户体验,所以自己就写了一个小的案例,仅仅师为例以后方便,
<template>
<div class="content">
<div class="title" id="title" @scroll="getscroll($event)">
<span v-for="(item,index) in title" @click="getleft($event,index)" :class="{blue:num==index}">{{item}}</span>
</div>
</div>
</template>
<script>
export default{
name:"TwoTitle",
data(){
return{
title:["新闻","体育","游戏","娱乐","财经","军事","媒体"],
num:0,
scrollLeft:"0"
}
},
mounted() {
},
methods:{
getleft(e,num){
this.num = num // 数组下标 根据数组下标添加class名称
var width = e.target.clientWidth //获取点击元素本身的宽度
console.log(this.scrollLeft)
var title = document.getElementById("title")
if (num==3 && this.scrollLeft ==0) { //判断当前位置 当超过一定界限时,滚动条滚动到底部,同时也可以自己设置滚动的距离
$(title).scrollLeft(width*2) //滚动条执行
} else if(num <= 2 && this.scrollLeft==150){
$(title).scrollLeft(-width*2)
}
},
getscroll(e){ //给标题的父元素添加滚动事件
this.scrollLeft = e.target.scrollLeft //记录滚动条滚动的距离
},
}
}
</script>
<style>
.title{ /*超出父元素时出现滚动条*/
width: 100%;
height: 45px;
overflow-x: auto;
overflow-y:hidden;
white-space: nowrap; /*超出父级元素是不换行*/
}
.title span{
display: inline-block;
width: 20%;
font-size: 40px;
text-align: center;
line-height: 45px;
}
.title::-webkit-scrollbar{
display: none;
}
.blue{
font-size: 45px;
color: blue;
border-bottom: 2px solid blue; /* px */
}
</style>
以上就是整个页面的代码,如果有朋友有更好的案例,看到之后,可以分享,谢谢!!!!!