效果预览

该效果来自抖音 @渡一前端
打开标签后,可以拖动图片,查看不同窗口的效果,可以拖动到其他窗口
打开新窗口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');

// 计算浏览器toolbar的高度
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)=>{
// 计算鼠标在图片中的坐标下x,y
let x = e.pageX - img.offsetLeft;
let y = e.pageY - img.offsetTop;
window.onmousemove = (e)=>{
// 计算图片当前拖动到的位置cx,cy
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;
};
};

最后更新: 2024年04月09日 21:36

原始链接: https://xiaguochang.github.io/posts/f9f311a7/