div中心跟踪鼠标动而动
得到鼠标坐标,移动时div的左上距离为鼠标两坐标减去div左上顶点到中心的距离
div任意位置随鼠标动而动
得到鼠标第一次坐标,移动时div的左上距离就为div每次移动前最开始的左上距离加上鼠标移动中的坐标减去鼠标第一次坐标,即任意位置移动是移动过程相对于第一次的位移
小div在大div内移动
在任意移动的基础上,判断div的最终左上边距,如果大于或小于大div的大小,则将小div的左右边界设置为临界值
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.div1{
height:100px;
width:100px;
background-color: orange;
position:absolute;
top:100px;
left: 100px;
}
</style>
</head>
<body>
<div class="div1">
</div>
<script>
var div1=document.querySelector(".div1");
var flag=false;
var mx=0;
var my=0;
var dx=0;
var dy=0;
div1.onmousedown=function(){
flag=true;
console.log("a");
mx=event.clientX;
my=event.clientY;
dx=div1.offsetLeft;
dy=div1.offsetTop;
}
document.onmousemove=function(){ //在整个html范围内滑动
if(flag){
var templeft=event.clientX;
var temptop=event.clientY;
div1.style.left=templeft-mx+dx+"px";
div1.style.top=temptop-my+dy+"px"; //样式任意位置随鼠标拖动而拖动
/*div1.style.left=templeft-50+"px";
div1.style.top=temptop-50+"px";*/ //样式中心随鼠标拖动而拖动
}
}
document.onmouseup=function()
{
flag=false;
}
</script>
</body>
</html>
小div在大div内移动
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.big{
width:500px;
height:500px;
border:solid 1px orange;
position: relative;
left:50px;
top:50px;
}
.small{
width:100px;
height:100px;
background-color:orange;
position:absolute;
left:50px;
top:100px;
}
</style>
</head>
<body>
<div class="big">
<div class="small">
</div>
</div>
<script>
var big=document.querySelector(".big");
var small=document.querySelector(".small");
var flag=false;
var cx;
var cy;
var sx;
var sy;
small.onmousedown=function(){
flag=true;
cx=event.clientX;
cy=event.clientY;
sx=small.offsetLeft;
sy=small.offsetTop;
console.log(cx,sx);
}
big.onmousemove=function(){
if(flag){
var ccx=event.clientX;
var ccy=event.clientY;
var resultx=sx+ccx-cx;
var resulty=sy+ccy-cy;
//确定边界
if(resultx<0)
{
resultx=0;
}
if(resultx>400)
{
resultx=400;
}
if(resulty<0)
{
resulty=0;
}
if(resulty>400)
{
resulty=400;
}
//结果
small.style.left=resultx+"px";
small.style.top=resulty+"px";
}
}
document.onmouseup=function(){
flag=false;
}
</script>
</body>
</html>