HTML部分
<div class="container">
</div>
css部分
@charset "gb2312";
/* CSS Document */
* {
margin: 0;
padding: 0;
}
body {
font-family: "微软雅黑";
background: url(../img/5-13050GTF9.png) repeat;
}
.container{ width:200px; height:200px; border:1px solid #000; position:absolute; top:0; left:0;}
js 部分
// JavaScript Document
$(document).ready(function(e) {var con=$('.container');
var MaxLeft=$(document).width()-con.outerWidth(true);
var MaxTop=$(document).height()-con.outerHeight(true);
//在电脑上移动的代码
con.mousedown(function(e){
var x1=e.pageX- parseInt(con.offset().left);
var y1=e.pageY- parseInt(con.offset().top);
$(document).mousemove(function(e){
var x=e.pageX;
var y=e.pageY;
xMove=x-x1;
yMove=y-y1;
var MoveLeft=xMove;
var MoveTop=yMove;
if(xMove>=MaxLeft){
MoveLeft=MaxLeft;
}
if(xMove<=0){
MoveLeft=0;
}
if(yMove>=MaxTop){
MoveTop=MaxTop;
}
if(yMove<=0){
MoveTop=0;
}
con.css({"top":MoveTop,"left":MoveLeft});
}).mouseup(function(){
$(this).unbind("mousemove");
});
});
//在手机上移动的代码
con.on("touchstart", function(e) {
e.preventDefault();
startX = e.originalEvent.changedTouches[0].pageX,
startY = e.originalEvent.changedTouches[0].pageY;
mx1=startX- parseInt(con.offset().left);
my1=startY- parseInt(con.offset().top);
});
con.on("touchmove", function(e) {
e.preventDefault();
moveEndX = e.originalEvent.changedTouches[0].pageX,
moveEndY = e.originalEvent.changedTouches[0].pageY;
xMove=moveEndX-mx1;
yMove=moveEndY-my1;
var MoveLeft=xMove;
var MoveTop=yMove;
if(xMove>=MaxLeft){
MoveLeft=MaxLeft;
}
if(xMove<=0){
MoveLeft=0;
}
if(yMove>=MaxTop){
MoveTop=MaxTop;
}
if(yMove<=0){
MoveTop=0;
}
con.css({"top":MoveTop,"left":MoveLeft});
});
});