我有一个函数,它从我的 SignalR
中心的另一个客户端接收 xy
坐标。每当 clientA
移动他的鼠标时,他的 xy 坐标
就会发送到 ClientB
。
我正在尝试在 clientB
屏幕上的 x-y
坐标处打印一个简单的 @
。这可行,但唯一的问题是它非常慢(我认为是因为每次鼠标移动 1px
时都会调用该函数)。当我在 clientA
上移动鼠标几秒钟时,clientB
屏幕上打印的“@”落后了。
这与我编写的用于显示此 @
的代码有什么关系吗?
hub.client.MouseMoved = function (x, y, id) {
id = "@"; //for testing purposes
var e = document.getElementById(id);
if (!e) { //if e is not found, create e
e = $('<div id="' + id + '">' + id + '</div>');
e.css('position', 'absolute');
console.dir(e);
$(e).appendTo(document.body);
}
else {
e = $(e);
}
e.css({ left: x + "px", top: y + "px" }); //set position of cursor to x y coordinate.
}
}
最佳答案
为了防止性能下降,您可以使用计时器:
var timer;
function executeMouseMoved(x, y, id){
id = "@"; //for testing purposes
var e = document.getElementById(id);
if (!e) { //if e is not found, create e
e = $('<div id="' + id + '">' + id + '</div>');
e.css('position', 'absolute');
console.dir(e);
$(e).appendTo(document.body);
}
else {
e = $(e);
}
e.css({ left: x + "px", top: y + "px" }); //set position of cursor to x y coordinate.
}
hub.client.MouseMoved = function (x, y, id) {
clearInterval(timer);
timer = setTimeout(function(){executeMouseMoved(x,y,id);}, 50); //50ms
}
希望对您有所帮助。
关于javascript - 每隔几毫秒在给定的 x-y 坐标上显示元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34288755/