jQuery 移动端拖动圆形div 实现:简单易懂的代码示例
<div id='circle'></div>
<style>
#circle {
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<script>
$(document).ready(function() {
var circle = $('#circle');
var isDragging = false;
var offset = { x: 0, y: 0 };
circle.on('mousedown touchstart', function(e) {
isDragging = true;
offset = getOffset(e);
e.preventDefault();
});
$(document).on('mouseup touchend', function() {
isDragging = false;
});
$(document).on('mousemove touchmove', function(e) {
if (isDragging) {
var pos = getOffset(e);
var x = pos.x - offset.x;
var y = pos.y - offset.y;
circle.css('left', x + 'px');
circle.css('top', y + 'px');
}
});
function getOffset(e) {
var offset = { x: 0, y: 0 };
if (e.type.indexOf('touch') === 0) {
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
offset.x = touch.pageX;
offset.y = touch.pageY;
} else {
offset.x = e.pageX;
offset.y = e.pageY;
}
return offset;
}
});
</script>
<p>这段代码使用了jQuery的'mousedown'、'mouseup'、'mousemove'和'touchstart'、'touchend'、'touchmove'事件来实现拖动功能。当鼠标按下或触摸开始时,设置'isDragging'为'true',并记录当前位置与圆形div的偏移量。在鼠标移动或触摸移动时,如果'isDragging'为'true',则计算新的位置并更新圆形div的'left'和'top'样式。</p>
<p>请注意,由于移动端的触摸事件与鼠标事件不同,因此我们需要使用'originalEvent.touches'来获取触摸点的位置。</p>
<p>希望对你有所帮助!</p>
原文地址: https://www.cveoy.top/t/topic/fo70 著作权归作者所有。请勿转载和采集!