除了默认提供的 4 个角外,我们还可以创建额外的 Control 占位符。
一个很好的优势是它允许在其中一个占位符中放置多个控件。它们将堆叠而不重叠,就像在标准角中一样。
JavaScript:
// Create additional Control placeholders
function addControlPlaceholders(map) {
var corners = map._controlCorners,
l = 'leaflet-',
container = map._controlContainer;
function createCorner(vSide, hSide) {
var className = l + vSide + ' ' + l + hSide;
corners[vSide + hSide] = L.DomUtil.create('div', className, container);
}
createCorner('verticalcenter', 'left');
createCorner('verticalcenter', 'right');
}
addControlPlaceholders(map);
// Change the position of the Zoom Control to a newly created placeholder.
map.zoomControl.setPosition('verticalcenterright');
// You can also put other controls in the same placeholder.
L.control.scale({position: 'verticalcenterright'}).addTo(map);
然后使用 CSS 为这些占位符设置样式就变得很容易了,因为它们的 DOM 父级就是地图容器本身。因此,top、bottom、left 和 right 可以用百分比指定(使用父级的尺寸)。
CSS:
.leaflet-verticalcenter {
position: absolute;
z-index: 1000;
pointer-events: none;
top: 50%; /* possible because the placeholder's parent is the map */
transform: translateY(-50%); /* using the CSS3 Transform technique */
padding-top: 10px;
}
.leaflet-verticalcenter .leaflet-control {
margin-bottom: 10px;
}
至于vertical centering 占位符本身,您可以使用自己喜欢的技术。这里我使用 CSS3 Transform 将占位符偏移其自身高度的一半。
如有必要(例如,为了旧浏览器的兼容性),您可以使用“calculate-on-load”方法来执行此偏移,类似于iH8's answer。但是您不再需要在调整地图大小时运行它,仅在将新控件添加到占位符时才需要。
现场演示:https://plnkr.co/edit/bHJwfm598d1Ps7MpLG0k?p=preview
注意:目前有一个公开的 PR (Leaflet/Leaflet #5554),但由于它与旧版本的 Internet Explorer 不兼容,因此不太可能合并到 Leaflet 核心中。