JSFiddle - React, Tailwind, and code Playground
HTML
<div class="box">
<img src="http://www.suapesquisa.com/mapas/mp-brasil.jpg" class="dragme" />
</div>
<div class="box">
<img src="http://www.suapesquisa.com/mapas/mp-brasil.jpg" class="dragme" />
</div>
<div class="box">
<img src="http://www.suapesquisa.com/mapas/mp-brasil.jpg" class="dragme" />
</div>
<div class="box">
<img src="http://www.suapesquisa.com/mapas/mp-brasil.jpg" class="dragme" />
</div>
<div class="box">
<img src="http://www.suapesquisa.com/mapas/mp-brasil.jpg" class="dragme" />
</div>
CSS
.box {
width: 100x;
height: 150px;
border: 1px solid #ccf;
overflow: hidden;
margin-bottom:6px;
}
.dragme {
position:relative;
}
JavaScript
var ondrag = {};
$('.dragme').on('mouseup touchend mouseout', toggleDrag);
$('.dragme').on('mousedown touchstart', toggleDrag);
$('.dragme').on('mousemove touchmove', drag);
function normalizarEvento(e) {
if (e.originalEvent.touches && e.originalEvent.touches.length) return e.originalEvent.touches[0];
return e;
}
function buscarPosicaoRelativa(el) {
var bodyRect = document.body.getBoundingClientRect();
var elemRect = el.getBoundingClientRect();
return {
x: elemRect.left - bodyRect.left,
y: elemRect.top - bodyRect.top
}
}
function toggleDrag(evt) {
evt.preventDefault();
var moveTouch = normalizarEvento(evt);
ondrag.on = evt.type == 'mousedown' || evt.type == 'touchstart';
if (ondrag.on) ondrag.start = {
x: moveTouch.clientX - this.getBoundingClientRect().left,
y: moveTouch.clientY - this.getBoundingClientRect().top
};
}
function toggleDrag(evt) {
evt.preventDefault();
var moveTouch = normalizarEvento(evt);
var posicaoElemento = buscarPosicaoRelativa(this);
ondrag.on = evt.type == 'mousedown' || evt.type == 'touchstart';
if (ondrag.on) ondrag.start = {
x: moveTouch.clientX - posicaoElemento.x + this.parentNode.getBoundingClientRect().left,
y: moveTouch.clientY - posicaoElemento.y + this.parentNode.getBoundingClientRect().top
};
}
function drag(evt) {
evt.preventDefault();
var moveTouch = normalizarEvento(evt);
if (!ondrag.on) return;
var x = moveTouch.clientX;
var y = moveTouch.clientY;
this.style.marginLeft = x - ondrag.start.x + 'px';
this.style.marginTop = y - ondrag.start.y + 'px';
}