简单的样式:
html,body{
padding: 0;
margin: 0;
height: 100%;
padding-top: 10%;
box-sizing: border-box;
}
.B{
width: 90%;
height: 90%;
margin: 0 auto ;
position: relative;
border: 1px solid red;
}
.box{
background-color: red;
width: 100px;
height: 100px;
}
创建一个操作空间和拖拽目标:
<div class="B">
<div class="box"></div>
</div>
功能实现:(需要引入JQ库)
$(".box").on({
//PC拖拽事件
mousedown: function (e) {
var T,L;
var el = $(this);
var os = el.offset();
var el_f = $(".B");
var os_f = el_f.offset();
var W = el_f.css("width").replace("px","")/1;
var w = el.css("width").replace("px","")/1;
var H = el_f.css("height").replace("px","")/1;
var h = el.css("height").replace("px","")/1;
var dx = e.pageX - os.left;
var dy = e.pageY - os.top;
$(document).on('mousemove.pc', function (e) {
T = e.pageY - dy;
L = e.pageX - dx;
if( T < os_f.top ){
T = os_f.top;
}
if( T > os_f.top+H-h ){
T = os_f.top + H - h;
}
if( L < os_f.left ){
L = os_f.left;
}
if( L > os_f.left+W-w ){
L = os_f.left + W - w;
}
el.offset({top:T , left: L});
});
},
mouseup: function () {
$(document).off('mousemove.pc');
},
//手机端拖拽事件
touchstart: function (e) {
e.preventDefault();
var T,L;
var el = $(this);
var os = el.offset();
var el_f = $(".B");
var os_f = el_f.offset();
var W = el_f.css("width").replace("px","")/1;
var w = el.css("width").replace("px","")/1;
var H = el_f.css("height").replace("px","")/1;
var h = el.css("height").replace("px","")/1;
var pageX = event.touches[0].clientX;
var pageY = event.touches[0].clientY;
$(document).on('touchmove.phone', function (e) {
e.preventDefault();
L = event.touches[0].clientX;
T = event.touches[0].clientY;
if( T < os_f.top ){
T = os_f.top;
}
if( T > os_f.top+H-h ){
T = os_f.top + H - h;
}
if( L < os_f.left ){
L = os_f.left;
}
if( L > os_f.left+W-w ){
L = os_f.left + W - w;
}
el.offset({top:T , left: L});
})
},
touchend : function (){
$(document).off('touchmove.phone');
}
});