效果预览
该效果来自抖音 @渡一前端
打开标签后,可以拖动图片,查看不同窗口的效果,可以拖动到其他窗口
打开新窗口1
打开新窗口2
HTML
1
| <img src="./images/logo.png" class="img" draggable="false">
|
CSS
1 2 3 4 5 6 7
| body { margin: 0; padding: 0; } .img { position: fixed; }
|
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| const img = document.querySelector('.img');
function barHeight(){ return window.outerHeight - window.innerHeight; }
function clientToScreen(x, y){ let screenX = x + window.screenX; let screenY = y + window.screenY + barHeight(); return [screenX, screenY]; }
function screenToClient(x, y){ let clientX = x - window.screenX; let clientY = y - window.screenY - barHeight(); return [clientX, clientY]; }
const channel = new BroadcastChannel("img")
channel.onmessage = (e)=>{ let [x, y] = screenToClient(...e.data) img.style.left = x + 'px'; img.style.top = y + 'px'; };
img.onmousedown = (e)=>{ let x = e.pageX - img.offsetLeft; let y = e.pageY - img.offsetTop; window.onmousemove = (e)=>{ let cx = e.pageX - x; let cy = e.pageY - y; img.style.left = cx + 'px'; img.style.top = cy + 'px'; let point = clientToScreen(cx, cy); channel.postMessage(point) }; window.onmouseup = (e)=>{ window.onmousemove = null; window.onmouseup = null; }; };
|