pc鼠标左右移动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PC端实现移动端滑动效果并与滚动条效果一致示例</title>
<style>
.box-wrap {
display: flex;
overflow: hidden;
white-space: nowrap;
}
.box {
flex: 0 0 auto;
width: 200px;
height: 200px;
background-color: lightblue;
margin-right: 10px;
}
</style>
</head>
<body>
<div class="box-wrap" style="overflow: auto;">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<script>
const boxWrap = document.querySelector('.box-wrap');
let isDragging = false;
let startX = 0;
let scrollLeft = 0;
boxWrap.addEventListener('mousedown', (e) => {
isDragging = true;
startX = e.clientX - boxWrap.offsetLeft;
scrollLeft = boxWrap.scrollLeft;
});
boxWrap.addEventListener('mousemove', (e) => {
if (!isDragging) return;
e.preventDefault();
const x = e.clientX - boxWrap.offsetLeft;
const walk = (x - startX) * 2; // 控制滑动速度
boxWrap.scrollLeft = scrollLeft - walk;
});
boxWrap.addEventListener('mouseup', () => {
isDragging = false;
});
boxWrap.addEventListener('mouseleave', () => {
isDragging = false;
});
</script>
</body>
</html>
本文来自博客园,作者:zjxgdq,转载请注明原文链接:https://www.cnblogs.com/zjxzhj/p/18101314

浙公网安备 33010602011771号