直接上源码吧,还需优化,总感觉不是很流畅
<style scoped>
* {
margin: 0;
padding: 0;
list-style: none;
}
.box {
width: 400px;
height: 200px;
margin: 100px auto;
position: relative;
overflow: hidden;
/* transition: property duration timing-function delay; */
scroll-behavior:smooth
}
.ul-list {
width: 2000px;
height: 200px;
line-height: 200px;
position: absolute;
display: flex;
background-color: red;
box-sizing: border-box;
transition: all 0.01s;
-webkit-transition: all 0.01s;
}
.ul-list li {
text-align: center;
width: 200px;
cursor: pointer;
}
.ul-list li:nth-child(odd) {
background-color: aqua;
}
.ul-list li:nth-child(even) {
background-color: #008c07;
}
</style>
<template>
<div id="bkg">
<div class="box" id="box1">
<ul class="ul-list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</div>
</div>
</template>
<script>
export default {
name: 'nav',
data () {
return {
}
},
components: {
},
methods:{
init(){
this.bindEvents()
},
bindEvents() {
// 鼠标按下时
this.ulList.onmousedown = e => {
e = e || window.event;
// e.offsetX获取到的是鼠标相对于li的坐标
// e.layerX获取到的是鼠标相对于ul(最近的有绝对定位的元素)的坐标
let disX = e.layerX;
// 鼠标移动时
document.onmousemove = e => {
e = e || window.event;
this.box.scrollLeft = this.box.offsetLeft - (e.clientX - disX);
}
// 鼠标弹起时
document.onmouseup = () => {
document.onmousemove = null;
}
// 取消默认行为
if (e.preventDefault) {
e.preventDefault();
} else {
return false;
}
}
},
getDom(selector){
this.box = document.querySelector(`#${selector}`);
this.ulList = this.box.querySelector('ul');
// 设置ul的宽度, ul的宽度跟随li的数量动态变化
this.ulList.style.width = this.ulList.querySelector('li').offsetWidth * this.ulList.querySelectorAll('li').length + 'px';
this.init();
}
},
created() {
},
mounted() {
let _this = this;
// 创建新的对象并传参
_this.getDom('box1');
},
}
</script>