模拟鼠标移动



考虑一下这个场景。用户在窗口内移动鼠标。我有窗口尺寸和鼠标坐标。例如:

let userInput = {
window: {
height: 822,
width: 1440
},
mouse: {
x: 1068,
x_pct: "74.167",
y: 1,
y_pct: "0.111"
}
}

在一个容器里,在另一扇窗户里。我想模拟鼠标移动,并将一个元素(如div(放置在与userInput中的鼠标位置类似的位置。

一个简单的解释是,如果用户的鼠标位于窗口的左上角,则将元素放置在容器的左上。

我可能走得太远了,但我觉得容器的宽度和高度必须相对于窗户的尺寸来考虑,才能将元素准确地放置在窗户中。因此,我不能只将对象放置在用户输入提供的相同位置,例如:

element.style.left = userInput.mouse.x + "px";
element.style.top = userInput.mouse.y + "px";

我觉得我需要想出一个公式或算法来实现这一点。感谢您的帮助。

这个简单的片段可以帮助您。

const myNewWindow = window.open("", "", "left=,top=10,width=320,height=320")
myNewWindow.document.write("<div id='target' style='position:absolute; background:red;'>Hello world!</div>")
document.addEventListener("mousemove", (e)=>{
const mainW = window.innerWidth;
const mainH = window.innerHeight;
const popW = myNewWindow.innerWidth;
const popH = myNewWindow.innerHeight;
myNewWindow.document.getElementById("target").style.top = e.clientY / mainH * popH;
myNewWindow.document.getElementById("target").style.left = e.clientX / mainW * popW;
});

这里有一个工作示例:https://jsfiddle.net/nogare/1tejzmux/
请注意,您需要启用弹出窗口。

最新更新