<!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>鼠标拖拽</title>
<style>
#box{
width: 100px;
height: 100px;
background: #f00;
position: absolute;
}
</style>
</head>
<body>
<div id="box">
</div>
</body>
<script>
var box = document.querySelector( '#box');
var clientW = document.documentElement.clientWidth;
var clientH = document.documentElement.clientHeight;
// box.onmousedown = function( eve ){
// var e = eve || window.event;
// var disX = e.offsetX;
// var disY = e.offsetY;
// document.onmousemove = function( eve ){
// // console.log( 1 )
// var e = eve || window.event;
// var x = e.pageX - disX;
// var y = e.pageY - disY;
// if( x < 0 ) x = 0 ;
// if( y < 0 ) y = 0;
// if( x > clientW - box.offsetWidth ) x = clientW - box.offsetWidth;
// if( y > clientH - box.offsetHeight ) y = clientH - box.offsetHeight;
// // console.log( x )
// box.style.left = x + 'px';
// // console.log( box.style.left )
// box.style.top = y + 'px';
// }
// document.onmouseup = function(){
// document.onmouseup = document.onmousemove = null;
// }
// }
function addEvent (ele,type,callback ){
if( ele.addEventListener){
ele.addEventListener(type,callback,false)
}else if( ele.attachEvent ){
ele.dattechEvent('on'+type,callback)
}else{
ele['on'+type] = callback;
}
}
function removeEvent( ele ,type,callback ){
if( ele.removeEventListener){
ele.removeEventListener(type,callback,false);
}else if( ele.detachEvent ){
ele.detachEvent('on'+type,callback ) ;
}else{
ele['on'+type] = null;
}
}
addEvent(box,'mousedown',function( eve ){
var e = eve || window.event;
var disX = e.offsetX;
var disY = e.offsetY;
addEvent(document,'mousemove',move);
addEvent(document,'mouseup',drag);
function drag( eve ){
var e = eve || window.event;
// document.onmouseup = document.onmousemove = null;
removeEvent(document,'mousemove',move);
removeEvent(document,'mousemoup',drag);
}
function move( eve ){
var e = eve || window.event;
var x = e.pageX - disX;
var y = e.pageY - disY;
if( x < 0 ) x = 0 ;
if( y < 0 ) y = 0;
if( x > clientW - box.offsetWidth ) x = clientW - box.offsetWidth;
if( y > clientH - box.offsetHeight ) y = clientH - box.offsetHeight;
box.style.left = x + 'px';
box.style.top = y + 'px';
}
})
</script>
</html>
网友评论