实现拖拽组件
<!DOCTYPE html
>
<html
>
<head
>
<meta charset
="utf-8">
<title
></title
>
<style type
="text/css">
position
: relative
;
width
: 200px
;
height
: 20px
;
background
: red
;
cursor
: move
;
}
.parent {
border
: 1px solid
position
: absolute
;
}
</style
>
</head
>
<body
>
<div
class="parent" id
='parent'>
<div id
="box"></div
>
<div
>
hello world
</div
>
<div
>welcome to login
</div
>
<form action
="">
<input type
="text" placeholder
="输入用户名字"><br
>
<input type
="password" placeholder
="输入用户名字"><br
>
<button type
='button'>login
</button
><br
>
</form
>
</div
>
</body
>
<script type
="text/javascript">
var box
= document
.getElementById("box");
var parent = document
.getElementById("parent");
</script
>
<script type
="text/javascript">
box
.onmousedown
= function(event
) {
var e
= event
|| window
.event
;
var dx
= event
.clientX
- parent.offsetLeft
var dy
= event
.clientY
- parent.offsetTop
if (typeof box
.setCapture
!== 'undefined') {
box
.setCapture();
}
document
.onmousemove
= function(e
) {
var e
= e
|| window
.event
var X
= e
.clientX
- dx
var Y
= e
.clientY
- dy
if (X
< 0) {
X
= 0
} else if (X
> window
.innerWidth
- parent.offsetWidth
) {
X
= window
.innerWidth
- parent.offsetWidth
}
if (Y
< 0) {
Y
= 0
} else if (Y
> window
.innerHeight
- parent.offsetHeight
) {
Y
= window
.innerHeight
- parent.offsetHeight
}
parent.style
.left
= X
+ 'px'
parent.style
.top
= Y
+ 'px'
}
document
.onmouseup
= function() {
this
.onmousemove
= null
this
.onmouseup
= null
if (typeof box
.releaseCapture
!= 'undefined') {
box
.releaseCapture()
}
}
}
</script
>
</html
>
转载请注明原文地址:https://ipadbbs.8miu.com/read-51849.html