效果
index.html
<! DOCTYPE html >
< html> < head> < title> card</ title> < link type = " text/css" rel = " styleSheet" href = " index.css" /> </ head> < body> < div id = " card" class = " card" > < img src = " A.png" /> </ div> < script src = " index.js" > </ script> </ body>
</ html>
index.css
* { margin : 0; padding : 0; box-sizing : border-box;
}
body { width : 100vw; height : 100vh; margin : 0; background : #fff;
}
.card { width : 100px; height : 200px; position : relative;
} img { width : 200px; height : 300px;
}
index.js
const card = document. querySelector ( '.card' ) ;
const BAR = 79 ;
function getClientPoint ( screenX, screenY ) { const clientX = screenX - window. screenX; const clientY = screenY - window. screenY- BAR ; return [ clientX, clientY] ;
}
function getScreenPoint ( clientX, clientY ) { const screenX = clientX + window. screenX; const screenY = clientY + window. screenY + BAR ; return [ screenX, screenY] ;
}
card. onmousedown = ( e ) => { let x = e. pageX - card. offsetLeft; let y = e. pageY - card. offsetTop; window. onmousemove = ( e ) => { const cx = e. pageX - x; const cy = e. pageY - y; card. style. left = cx + 'px' ; card. style. top = cy + 'px' ; console. log ( e) ; console. log ( channel) ; channel. postMessage ( getScreenPoint ( cx, cy) ) ; } ; window. onmouseup = ( e ) => { window. onmousemove = null ; window. onmouseup = null ; } ;
} ; function init ( ) { if ( location. search. includes ( 'hidden' ) ) { card. style. left = '-1000px' ; }
} init ( ) ;
const channel = new BroadcastChannel ( 'card' ) ;
channel. onmessage = ( e ) => { const [ cx, cy] = getClientPoint ( ... e. data) ; card. style. left = cx + 'px' ; card. style. top = cy + 'px' ;
}
A.png