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>

  

posted @ 2024-03-28 12:06  zjxgdq  阅读(6)  评论(0编辑  收藏  举报