1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| class ImageSlider { constructor(mask, leftImage, rightImage, widthPercent) { this.mask = mask; this.leftImage = leftImage; this.rightImage = rightImage; this.isDragging = false;
this.mask.style.left = (widthPercent - 0.5) + '%'; this.leftImage.style.clipPath = 'inset(0 ' + (100 - widthPercent) + '% 0 0)'; this.rightImage.style.clipPath = 'inset(0 0 0 ' + widthPercent + '%)';
this.mask.addEventListener('touchstart', (e) => { this.isDragging = true; e.preventDefault(); }); document.addEventListener('touchend', () => { this.isDragging = false; }); document.addEventListener('touchmove', (e) => { if (this.isDragging) { this.touchDrag(e); } });
this.mask.addEventListener('mousedown', (e) => { this.isDragging = true; e.preventDefault(); }); document.addEventListener('mouseup', () => { this.isDragging = false; }); document.addEventListener('mousemove', (e) => { if (this.isDragging) { this.drag(e); } }); }
touchDrag(e) { var rect = this.mask.parentNode.getBoundingClientRect(); var x = e.touches[0].clientX - rect.left; var widthPercent = (x / rect.width) * 100; widthPercent = Math.min(Math.max(widthPercent, 0.5), 99.5); this.mask.style.left = (widthPercent - 0.5) + '%'; this.leftImage.style.clipPath = 'inset(0 ' + (100 - widthPercent) + '% 0 0)'; this.rightImage.style.clipPath = 'inset(0 0 0 ' + widthPercent + '%)'; }
drag(e) { var rect = this.mask.parentNode.getBoundingClientRect(); var x = e.clientX - rect.left; var widthPercent = (x / rect.width) * 100; widthPercent = Math.min(Math.max(widthPercent, 0.5), 99.5); this.mask.style.left = (widthPercent - 0.5) + '%'; this.leftImage.style.clipPath = 'inset(0 ' + (100 - widthPercent) + '% 0 0)'; this.rightImage.style.clipPath = 'inset(0 0 0 ' + widthPercent + '%)'; } }
function createImageSlider(sliderId, widthPercent=50) { const slider = document.getElementById(sliderId); const mask = slider.querySelector('.mask'); const leftImage = slider.querySelector('.left-image'); const rightImage = slider.querySelector('.right-image'); return new ImageSlider(mask, leftImage, rightImage, widthPercent); }
|