为传单 L.Draggable 对象设置包含

Set containment for leaflet L.Draggable object

我在地图上有一个可拖动的 window(在我的例子中是 https://github.com/mapshakers/leaflet-control-window),我想用地图框限制其可拖动区域以防止它超出可见范围 space 并且无法将其拖回。

var draggable = new L.Draggable(this._container,this._containerTitleBar);
draggable.enable();

它是使用上面的代码创建的,但是无法传递 jQuery

中提供的包含元素
$('#elem').draggable({axis: 'y', containment : [0,containmentTop,0,containmentBottom] });

我确定一定有一种方法可以使用 L.Draggable 来限制拖动区域,而不是使用 Jquery 的可拖动对象。

您可以覆盖 showOn 函数:

marker.off();
marker.on('click',function(){

        var win =  L.control.window(map,{title:'Hello world!',maxWidth:400,modal: true})
                .content('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ac sollicitudin eros, ut imperdiet felis. Pellentesque pretium mi ante, et faucibus ipsum rutrum sed. Proin accumsan luctus consectetur. In sit amet purus id dui scelerisque ultricies non porta dui. Cras sit amet arcu non est efficitur molestie.')
                .prompt({callback:function(){alert('This is called after OK click!')}})
                //.show()

win.showOn = function(point){
        this.setContentMaxHeight();
        L.DomUtil.setPosition(this._container, L.point(Math.round(point[0]),Math.round(point[1]),true));

        var draggable = new L.Draggable(this._container,this._containerTitleBar);

        draggable.enable();
        draggable.off().on('drag',function(e){
        var pos = e.sourceTarget._newPos;
        var winwidth = map._container.clientWidth-win._container.clientWidth-16;
        var winheight = map._container.clientHeight-win._container.clientHeight-16;
        if(pos.x <= 0 || pos.y <=0 || pos.x >= winwidth || pos.y >= winheight){
            if(pos.x <= 0){
                pos.x = 0;
            }
            if(pos.y <= 0){
                pos.y = 0;
            }
            if(pos.x >= winwidth){
                pos.x = winwidth;
            }
            if(pos.y >= winheight){
                pos.y = winheight;
            }
            L.DomUtil.setPosition(win._container, L.point(pos.x,pos.y));
        }
    });

        L.DomUtil.addClass(this._wrapper, 'visible');
        this.fire('show');
        return this;
    }
    win.show();
    });

我使用此页面进行测试:http://mapshakers.com/projects/leaflet-control-window/

将上面的代码粘贴到开发者控制台,然后点击标记