JavaScript拖拽事件
div拖拽案例:
html
.kong{
width: 200px;
height: 100px;
background-color: yellowgreen;
font-size: 32px;
text-align: center;
position: relative;
top: 92px;
left: 92px;
}
<div class="kong" id="test"></div>
JavaScript
<script>
//拖拽事件
var ele = document.getElementById("test");
ele.onmousedown = function (ev) {
var x1,y1,x2,y2,x,y,l,t,l2,t2;
var ev = ev || event;
l = ele.offsetLeft;
t = ele.offsetTop;
x1 = ev.clientX;
y1 = ev.clientY;
document.onmousemove = function (ev) {
var ev = ev || event;
x2 = ev.clientX;
y2 = ev.clientY;
x = x2-x1;
y = y2-y1;
l2 = x + l;
t2 = y+ t;
ele.style.left = l2+'px';
ele.style.top = t2+'px';
};
document.onmouseup = function(ev){
document.onmousemove = null;
};
};
</script>
效果图: