Press "Enter" to skip to content

实现滑块控制左右侧对比图效果

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>图片拼接对比效果</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="left-image">
        </div>
        <div class="right-image">
        </div>
        <div class="slider">
            <div class="handle"></div>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>
body {
    margin: 0;
    padding: 0;
}

.container {
    position: relative;
    width: 300px; /* 根据需要调整宽度 */
    height: 300px; /* 根据需要调整高度 */
    overflow: hidden;
    user-select: none; /* 防止选中文本 */
}

.left-image,
.right-image {
    position: absolute;
    top: 0;
    bottom: 0;
    overflow: hidden;
}

.left-image {
    width: 50%;                     /* 设置容器宽度为100px */
    height: 300px;                    /* 设置适当的高度,根据图片高度调整 */
    background-image: url('https://fastly.picsum.photos/id/483/300/300.jpg?hmac=d1d3gQIl9j5Z_Ir03R3RU74CDPsFnhiYzSD0d0WuQv0');
    background-position: left center;/* 定位到右侧 */
    background-repeat: no-repeat;     /* 不重复 */
    background-size: 300px auto;      /* 保持原始宽度 */
}

.right-image {
    width: 50%;                     /* 设置容器宽度为100px */
    height: 300px;               /* 设置适当的高度,根据图片高度调整 */
    left:50%;
    background-image: url('https://fastly.picsum.photos/id/364/300/300.jpg?hmac=Jc5K7zP1K2ZsBWPGk6c4raWWOuYXzXz7Gj6LXNpuq6s');
    background-position: right center;/* 定位到右侧 */
    background-repeat: no-repeat;     /* 不重复 */
    background-size: 300px auto;      /* 保持原始宽度 */
}

.slider {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 50%; /* 初始位置在中间 */
    width: 2px;
    background-color: #fff;
    cursor: ew-resize;
}

.handle {
    position: absolute;
    top: 0;
    left: -10px;
    width: 20px;
    height: 100%;
    background-color: transparent;
}

const container = document.querySelector('.container');
const leftImage = document.querySelector('.left-image');
const rightImage = document.querySelector('.right-image');
const slider = document.querySelector('.slider');
let isDragging = false;

slider.addEventListener('mousedown', function () {
    isDragging = true;
});

window.addEventListener('mouseup', function () {
    isDragging = false;
});

window.addEventListener('mousemove', function (e) {
    if (!isDragging) return;

    let rect = container.getBoundingClientRect();
    let offsetX = e.clientX - rect.left;

    // 确保滑块在容器范围内
    if (offsetX < 0) offsetX = 0;
    if (offsetX > rect.width) offsetX = rect.width;

    // 计算百分比
    let percent = (offsetX / rect.width) * 100;

    // 调整左、右图片容器的宽度
    leftImage.style.width = percent + '%';
    rightImage.style.width = 100 - percent + '%';
    // 调整右图片容器的位置
    rightImage.style.left = percent + '%';

    // 调整滑块的位置
    slider.style.left = offsetX + 'px';
});

https://jsfiddle.net/pgLsd13u

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注