今天突然接到一个业务,要实现横向拖拽滚动,废话不多说直接上代码。记录一下以免以后遇到相同需求
html部分
<div class="ranking-container">
<div class="ranking-list">
<div class="ranking-item">
<img src="./images/No.1.png" alt="">
<p class="company-name">公司名称</p>
<p class="ranking-date">创建时间</p>
</div>
</div>
</div>
css部分
.ranking-container{
overflow: hidden;
}
.ranking-list{
position: relative;
display: flex;
flex-wrap: nowrap;
scroll-behavior: smooth;
width: 100%;
margin-top: 20px;
cursor: move;
/* overflow-x: scroll; */
transition: transform 0.2s;
}
.ranking-item{
padding-right: 15px;
font-size: 12px;
color: #DAF3FC;
}
.ranking-item img{
display: block;
draggable: false;
pointer-events: none;
-webkit-user-drag: none;
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
.ranking-item .company-name{
width: 62px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
margin-top: 15px;
margin-bottom: 5px;
pointer-events: none;
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
.ranking-item .ranking-date{
color: #DAF3FC;
opacity: 0.7;
pointer-events: none;
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
js
const doms = {
rankingListEl: document.querySelector('.ranking-list'),
}
var isMouseDown = false,
scroll = {
// 鼠标按下时的位置
mouseDownX: 0,
// 鼠标停止移动时的位置
mouseMoveOver: 0,
//排行列表当前的X轴位置
listX: 0,
// 向左最大拖拽距离
maxLeftX: doms.rankingListEl.clientWidth - doms.rankingListEl.scrollWidth,
};
doms.rankingListEl.addEventListener('mousedown', function (e) {
// 鼠标左键按下
if (e.button === 0) {
isMouseDown = true
scroll.mouseDownX = e.clientX
scroll.mouseMoveOver = null
}
})
// 监听鼠标移动事件
document.addEventListener('mousemove', function (e) {
e.preventDefault()
if (isMouseDown) {
let moveDist = scroll.mouseMoveOver === null?e.clientX - scroll.mouseDownX:e.clientX - scroll.mouseMoveOver
// 鼠标向右移动
if (moveDist > 0) {
if (scroll.listX < 0) {
if (scroll.listX + moveDist > 0) {
doms.rankingListEl.style.transform = `translateX(${0}px)`
scroll.listX = 0
} else {
doms.rankingListEl.style.transform = `translateX(${scroll.listX + moveDist}px)`
scroll.listX = scroll.listX + moveDist
}
}
} else {
// 鼠标向左移动
if (scroll.listX > scroll.maxLeftX) {
if ((scroll.listX + moveDist) < scroll.maxLeftX) {
doms.rankingListEl.style.transform = `translateX(${scroll.maxLeftX}px)`
scroll.listX = scroll.maxLeftX
} else {
doms.rankingListEl.style.transform = `translateX(${scroll.listX+moveDist}px)`
scroll.listX = scroll.listX + moveDist
}
}
}
scroll.mouseMoveOver = e.clientX
}
})
// 监听鼠标抬起事件
document.addEventListener('mouseup', function(e) {
isMouseDown = false
doms.rankingListEl.clientWidth
})