<div class="slider__cotainer">
<div id="image-comparison">
<img src="" alt="alt">
<img src="" alt="alt">
</div>
</div>
<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/slider__beforeafter.js" ></script>
.slider__cotainer{
margin: 0 auto;
max-width: 300px;
}
.image-comparison {
position: relative;
display: inline-block;
width: 100px;
width: 100%;
max-width: 500px;
overflow: hidden;
}
.image-comparison__before {
position: absolute;
width: 50%;
overflow: hidden;
}
.image-comparison__image {
display: block;
}
/* Ползунок */
.image-comparison__slider {
padding: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 2px;
height: 100%;
background-color: wheat;
border-radius: 100%;
cursor: col-resize;
}
/* Стрелки */
.image-comparison__slider::before {
content: '';
position: absolute;
top: calc(50% - 15px);
left: -14px;
width: 30px;
height: 30px;
border-radius: 50%;
background: transparent url('./img/arrows.png') no-repeat center;
border: 2px solid #fff;
background-size: 90%;
}
.image-comprison__slider:hover,
.image-comprison__slider:focus,
.image-comprison__slider:hover::before,
.image-comprison__slider:focus::before {
background-color: wheat
}
function imageComparison(selector) {
let comparison = $(selector)
.addClass('image-comparison')
.prepend('<div class="image-comparison__before"></div>')
.append('<button class="image-comparison__slider"></button>');
let images = comparison
.find('img')
.addClass('image-comparison__image')
.css('max-width', comparison.width());
let before = comparison
.find('.image-comparison__before')
.append(images.eq(0));
comparison
.find('.image-comparison__slider')
.on('dragstart', () => false) // отмена станд. drug&drop
.on('mousedown', function(e) {
let slider = $(this);
let doc = $(document).on('mousemove', (e) => {
let offset = e.pageX - comparison.position().left;
let width = comparison.width();
// установим границы, чтобы ползунок не выходил
if (offset < 0) offset = 0;
if (offset > width) offset = width;
slider.css('left', offset + 'px');
before.css('width', offset + 'px');
});
doc.on('mouseup', () => doc.off('mousemove'));
});
};
imageComparison('#image-comparison');