1、vue中, 我们要实现以下效果,多个菜单一行放置不下,被挡住,点击不了。这时候我们考虑用鼠标移动拖拽,对菜单进行拖拽操作,点击
![](https://img.haomeiwen.com/i15765796/1936d5647c825510.png)
image.png
2. 实现代码如下: html
// 给当前 h-tabs 增加 ref 属性,方便在 js 中获取该元素。
<h-tabs ref="tabs" type="card" size="small" v-if="tabData.length > 1" > </h-tabs>
3. js
<script>
let target, intX, scrollLeft;
export default {
watch: {
tabData (val) {
this.$nextTick(() => {
if (val.length > 0) {
this.$refs.tabs.$el.querySelector('.h-tabs-nav-wrap').style.float = 'none';
target = this.$refs.tabs.$refs.nav;
Object.assign(target.style, {
display: 'flex',
overflow: 'hidden',
'user-select': 'none'
})
target.onmousedown = (e) => {
// 鼠标到窗口左侧的距离
intX = e.clientX;
// tarb的滚动条左侧的距离
scrollLeft = e.currentTarget.scrollLeft;
// 监听鼠标移动事件
document.addEventListener('mousemove', this.dragMove)
}
// 监听鼠标松开事件
document.addEventListener('mouseup', this.dcMouseUp);
// 禁止拖拽
target.ondrop = function (e) {
e.preventDefault();
}
target.ondragstart = function (e) {
e.preventDefault();
}
target.ondragend = function (e) {
e.preventDefault();
}
}
})
}
},
methods: {
// 滚动条移动了多少距离==鼠标移动的距离
dragMove (e) {
target.scrollLeft = scrollLeft + (intX - e.clientX);
},
// 取消鼠标移动监听事件
dcMouseUp () {
document.removeEventListener('mousemove', this.dragMove);
},
}
}
</script>
4. this.
el.querySelector('.h-tabs-nav-wrap' )指哪如下元素
![](https://img.haomeiwen.com/i15765796/6f6a0945752861ad.png)
image.png
网友评论