<!DOCTYPE html>
<html
lang=
"en"
>
<head>
<meta
charset=
"UTF-8"
>
<meta
name=
"viewport"
content=
"width=device-width, initial-scale=1.0"
>
<meta
http-equiv=
"X-UA-Compatible"
content=
"ie=edge"
>
<title>Document
</title>
<style>
* {
padding:
0;
margin:
0;
}
#
big {
width:
500
px;
height:
500
px;
background-color:
#ccc;
position:
relative
}
#
box {
width:
100
px;
height:
100
px;
background-color:
#f00;
position:
absolute
}
<
/style>
<script>
window
.
onload
=
function
()
{
var
box
=
document
.
getElementById
(
'box'
);
var
big
=
document
.
getElementById
(
'big'
);
// 鼠标在box中的位置
var
disX
=
0
,
disY
=
0
;
box
.
onmousedown
=
function
(
e
)
{
var
thisE
=
e
||
event
;
disX
=
thisE
.
clientX
-
box
.
offsetLeft
;
disY
=
thisE
.
clientY
-
box
.
offsetTop
;
document
.
onmousemove
=
function
(
ev
)
{
var
thisEvent
=
ev
||
event
;
var
l
=
thisEvent
.
clientX
-
disX
;
var
t
=
thisEvent
.
clientY
-
disY
;
if
(
l
<
20
)
{
l
=
0
;
}
else
if
(
l
>
big
.
offsetWidth
-
box
.
offsetWidth
-
20
)
{
l
=
big
.
offsetWidth
-
box
.
offsetWidth
;
}
if
(
t
<
20
)
{
t
=
0
;
}
else
if
(
t
>
big
.
offsetHeight
-
box
.
offsetHeight
-
20
)
{
t
=
big
.
offsetHeight
-
box
.
offsetHeight
;
}
box
.
style
.
left
=
l
+
'px'
;
box
.
style
.
top
=
t
+
'px'
;
document
.
onmouseup
=
function
()
{
document
.
onmousemove
=
null
;
document
.
onmouseup
=
null
;
}
}
e
.
preventDefault
();
}
}
<
/script>
</head>
<body>
<div
id=
"big"
>
<div
id=
"box"
></div>
</div>
</body>
</html>