自定义光标在浏览器窗口之外

V02*_*460 8 javascript window cursor

我的网站上有一个可自由调整大小的元素.这是通过边缘上的4个手柄完成的.在悬停这些句柄时,在调整元素大小时,我想显示相应的调整大小箭头.

目前,我通过将body/root的css游标样式设置为这些箭头来实现此行为.它的问题是浏览器窗口的客户区域的限制.如果在按住鼠标时箭头光标随处可见,那么它在视觉上会更加一致并且不那么混乱.

谷歌地图在移动地图时用手形光标做同样的事情.所以我的问题是如何实现这个效果.

我目前(相关)的来源:

function startObjectScaling(e){
    e.stopPropagation();
    e.preventDefault();
    document.documentElement.style.cursor = this.style.cursor;
    window.addEventListener("mouseup", stopObjectScaling, false);
}

function stopObjectScaling(e){
    e.stopPropagation();
    document.documentElement.style.cursor = '';
    window.removeEventListener("mouseup", stopObjectScaling);
}

[...]

var tg = document.getElementById("transformGadget");
var handle = tg.firstChild.nextSibling;
for(var i=0;i<4;i++){
    handle.addEventListener("mousedown", startObjectScaling, false);
    handle = handle.nextSibling;
}
Run Code Online (Sandbox Code Playgroud)

V02*_*460 5

为此目的,在更现代的浏览器中实现了一个特殊的功能。名称是setCapture()。它将所有鼠标输入重定向到调用该方法的对象。现在,该元素上的简单 css光标定义就足以实现所需的效果。释放鼠标后,此效果将停止(确保安全)。也可以通过调用releaseCapture手动停止

例子:

<style type="text/css">
#testObj {
    /* this cursor will also stay outside the window.
       could be set by the script at the mousedown event as well */
    cursor: hand;
}
</style>
Run Code Online (Sandbox Code Playgroud)

[...]

document.getElementById('testObj').onmousedown = function(e){

    // these 2 might be useful in this context as well
    //e.stopPropagation();
    //e.preventDefault();

    // here is the magic
    e.target.setCapture();
}
Run Code Online (Sandbox Code Playgroud)