Skip to content

Instantly share code, notes, and snippets.

@pramper
Last active July 29, 2016 00:45
Show Gist options
  • Save pramper/579f13f8043d08b9c9791107a7855454 to your computer and use it in GitHub Desktop.
Save pramper/579f13f8043d08b9c9791107a7855454 to your computer and use it in GitHub Desktop.
一个传统的HTML元素拖放方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
position: absolute;
width: 200px;
left: 0;
top: 0;
}
#box-header{
width: 100%;
height: 30px;
background-color: #fcc;
cursor: move;
}
#box-content{
width: 100%;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div id="box">
<div id="box-header"></div>
<div id="box-content"></div>
</div>
<script>
var drag = (function() {
var flag = false // 表示是否拖曳
/**
* @param {[element]} bar:点击的元素,如登录框的头部
* @param {[element]} target:被拖曳的元素
*/
function startDrag(bar, target) {
var innerX, innerY // 鼠标距bar的左边距和上边距的距离
bar.addEventListener('mousedown', mousedown, false)
document.addEventListener('mouseup', mouseup, false)
document.addEventListener('mousemove', mousemove, false)
//获取target的CSS
var targetCSS = document.defaultView.getComputedStyle(target, null)
function mousedown() {
flag = true //鼠标点下时,表示才能被拖曳
innerX = event.clientX - parseInt(targetCSS.left)
innerY = event.clientY - parseInt(targetCSS.top)
}
function mousemove() {
if(flag) {
target.style.left = event.clientX - innerX + 'px'
target.style.top = event.clientY - innerY + 'px'
}
}
function mouseup() {
flag = false //松开鼠标后,元素无法被拖曳
}
}
return startDrag
})();
</script>
<script>
var header = document.getElementById('box-header')
var box = document.getElementById('box')
drag(header, box)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment