简体   繁体   中英

OpenLayers6 Detect when cursor leaves map

I want to hide a circle that is attached to the cursor when the cursor leaves the map. This circle must also hide when the cursor enters a ol.control . In older OL versions I simply added a mouseleave listener to the canvas object, but in OL6 it is not guaranteed that a canvas exists and the propagation of those basic events seem to be stopped for all elements below ol-viewport .

How can I achieve this behavior in OL6?

You will need separate listeners for the controls. My code for a context menu (not active on controls) looks like

var controlOver = false;

function setControlOver(element) {
    element.addEventListener('mouseover', function() { controlOver = true; });
    element.addEventListener('mouseout', function() { controlOver = false; });
}

setTimeout(function() {
    var controls = map.getViewport().getElementsByClassName('ol-control');
    for (var i=0; i<controls.length; i++) {
        setControlOver(controls[i]);
    }
    map.getControls().on('add', function(e) {
        // ????? setControlOver(e.element.getElement());
    });
}, 250);

map.getOverlays().on('add', function(e) {
    setControlOver(e.element.getElement());
});

var canvas = map.getViewport().getElementsByClassName('ol-overlaycontainer-stopevent')[0];

canvas.addEventListener('contextmenu', function (e) {
    if (!controlOver) {
        e.preventDefault();
        openContextMenu(e.x, e.y);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM