< div class = " mark" > < h1> title</ h1> < div> < p> title 鼠标移动 盒子整体移动</ p> < p> test</ p> < p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Modi, porro.</ p> </ div> </ div>
const mark = document. querySelector ( ".mark" ) const title = document. querySelector ( "h1" ) title. onmousedown = function ( e ) { let x = e. clientX; let y = e. clientY; let markrect = mark. getBoundingClientRect ( ) ; console. log ( markrect) let clientW = document. documentElement. clientWidth; let clientH = document. documentElement. clientHeight; let markW = mark. offsetWidth; let markH = mark. offsetHeight; let maxLeft = clientW - markW; let maxTop = clientH - markH; console. log ( markW, markH) console. log ( maxLeft, maxTop) window. onmousemove = function ( e ) { let disX = e. clientX - x; let disY = e. clientY - y; let left = markrect. left + disX; let top = markrect. top + disYif ( left < 0 ) { left = 0 ; } else if ( left > maxLeft) { left = maxLeft} if ( top < 0 ) { top = 0 ; } else if ( top > maxTop) { top = maxTop} mark. style. top = top + "px" ; mark. style. left = left + "px" ; } window. onmouseup = function ( ) { console. log ( "up" ) window. onmousemove = null ; window. onmouseup = null ; } }