先上效果图
附上代码
<! DOCTYPE html >
< html lang = " en" > < head> < meta charset = " UTF-8" /> < meta http-equiv = " X-UA-Compatible" content = " IE=edge" /> < meta name = " viewport" content = " width=device-width, initial-scale=1.0" /> < title> Document</ title> < style> .four { width : 200px; height : 100px; background-color : #00f; position : relative; } </ style>
</ head> < body> < div class = " four" style = " top : 0; left : 0" > </ div> < script> var div = document. getElementsByTagName ( 'div' ) [ 0 ] ; function drag ( ) { var disX, disY; div. addEventListener ( 'mousedown' , function ( e ) { var e = e || window. event; disX = e. pageX - parseInt ( div. style. left) ; disY = e. pageY - parseInt ( div. style. top) ; document. addEventListener ( 'mousemove' , move) ; document. addEventListener ( 'mouseup' , function ( e ) { document. removeEventListener ( 'mousemove' , move) ; } ) } ) function move ( e ) { var e = e || window. event; div. style. left = ( e. pageX - disX) + 'px' ; div. style. top = e. pageY - disY + 'px' ; } } drag ( ) </ script>
</ body> </ html>