HTML:
<div style="width: 100px; height: 100px; background-color: darkgray; position:absolute;left: 0px; top: 0px;" id="barrage"></div>
js:
/*拖动事件*/
var cont=$("#barrage");
var contW=$("#barrage").width();
var contH=$("#barrage").height();
var startX,startY,sX,sY,moveX,moveY, disX, disY;
var winW=$(window).width();
var winH=$(window).height();
cont.on({//绑定事件
touchstart:function(e){
startX = e.originalEvent.targetTouches[0].pageX; //获取点击点的X坐标
startY = e.originalEvent.targetTouches[0].pageY; //获取点击点的Y坐标
//console.log("startX="+startX+"************startY="+startY);
sX=$(this).offset().left;//相对于当前窗口X轴的偏移量
sY=$(this).offset().top;//相对于当前窗口Y轴的偏移量
//console.log("sX="+sX+"***************sY="+sY);
leftX=startX-sX;//鼠标所能移动的最左端是当前鼠标距div左边距的位置
rightX=winW-contW+leftX;//鼠标所能移动的最右端是当前窗口距离减去鼠标距div最右端位置
topY=startY-sY;//鼠标所能移动最上端是当前鼠标距div上边距的位置
bottomY=winH-contH+topY;//鼠标所能移动最下端是当前窗口距离减去鼠标距div最下端位置
},
touchmove:function(e){
e.preventDefault();
moveX=e.originalEvent.targetTouches[0].pageX;//移动过程中X轴的坐标
moveY=e.originalEvent.targetTouches[0].pageY;//移动过程中Y轴的坐标
//console.log("moveX="+moveX+"************moveY="+moveY);
if(moveX<leftX){moveX=leftX;}
if(moveX>rightX){moveX=rightX;}
if(moveY<topY){moveY=topY;}
if(moveY>bottomY){moveY=bottomY;}
$(this).css({
"left":moveX+sX-startX,
"top":moveY+sY-startY,
});
},
mousedown: function(ev){
var patch = parseInt($(this).css("height"))/2;
//console.log(patch);
$(this).mousemove(function(ev){
var oEvent = ev || event;
//console.log(oEvent.target);
var oX = oEvent.clientX;
var oY = oEvent.clientY;
var t = oY - patch;
var l = oX - patch;
var w = $(window).width() - $(this).width();
var h = $(window).height() - $(this).height();
if(t<0){t = 0}
if(l<0){l=0}
if(t>h){t=h}
if(l>w){l=w}
$(this).css({top:t,left:l})
});
$(this).mouseup(function(){
$(this).unbind('mousemove');
});
}
});
另附一种pc端原生js的写法:
window.onload = function () {
var oDiv = document.getElementById('oDiv');
var disX = 0, disY = 0;
oDiv.onmousedown = function (ev) {
var oEvent = ev || event;
disX = oEvent.clientX - oDiv.offsetLeft;
disY = oEvent.clientY - oDiv.offsetTop;
document.onmousemove = function (ev) {
var oEvent = ev || event;
var l = oEvent.clientX - disX;
var t = oEvent.clientY - disY;
console.log(l);
if(l <= 0){ l = 0}
if(t < 0){t = 0}
if(l > document.documentElement.clientWidth - oDiv.offsetWidth){
l = document.documentElement.clientWidth - oDiv.offsetWidth;
}
if(t > document.documentElement.clientHeight - oDiv.offsetHeight){
t = document.documentElement.clientHeight - oDiv.offsetHeight;
}
oDiv.style.left = l + 'px';
oDiv.style.top = t + 'px';
}
document.onmouseup = function (ev) {
document.onmousemove = null;
document.onmouseup = null;
}
}
}