每隔几毫秒在给定的x-y坐标上显示元素

时间:2015-12-15 12:01:56

标签: javascript jquery html mouseevent

我有一个函数,从xy集线器中的另一个客户端收到SignalR坐标。只要clientA移动鼠标,他的xy-coordinate就会被发送到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.
        }
    }

1 个答案:

答案 0 :(得分:1)

为防止性能下降,您可以使用计时器:

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
}

希望它有所帮助。

JsFiddle