在Leaflet地图上添加可点击的按钮

5
我希望在我的Leaflet地图的右上角(距离顶部和右侧20像素)添加一个按钮。问题是我不确定如何正确地实现这一点。问题在于当我使用"leaflet-top leaflet-right"类时,我的按钮无法点击,并且当我将鼠标悬停在其上时,没有任何反应。它只是保持为地图的一部分。
以下是我的HTML代码:
        <div id="mainContainer">
            <div id="mapDiv">
                <div id="map">
                    <div class="leaflet-top leaflet-right">
                        <div id="refreshButton"><div id="refreshButtonPictogram"><img src="pictograms/refresh.png" height="30px"></div></div>
                    </div>>
                </div>  
            </div>          
            <div id="bars"></div>
        </div>

这里是我的CSS:
#mainContainer{
    position: relative;
    width: 100%;
    height: calc(100% - 80px);
    display: flex;
}

#bars{
    z-index: 0;
    width: 500px;
    overflow-x: auto;
    border-left: 1px solid rgb(214, 49, 65);
}

::-webkit-scrollbar {
    display: none;
}

#mapDiv {
    flex: 1;
}
#map {
    width: 100%;
    height: 100%;
    z-index: 0;
}

#refreshButton{
    display: flex;
    align-items: center;
    position: relative;
    top: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
    background-color: white;
    border-radius: 5px;
    border-color: gray;
    border-style: solid;
    border-width: 1px 1px 1px 1px;
    opacity: 0.6;
    text-align: center;
}
#refreshButton:hover{
    opacity: 0.8;
    cursor: pointer;
}

#refreshButtonPictogram{
    margin: auto;
}


@media screen and (max-width: 500px) { 
  #mainContainer {
    flex-direction: column; 
  }
  #mapDiv,
  #bars {
    flex: 1;
  }
}

你是否设置了 z-index 属性?如果你的按钮无法点击,我认为你应该尝试操作 z-index。 - user7776077
是的,我甚至尝试将#refreshButton的z-index设置为10000,但它仍然没有起作用。 - mato
其他的z-index怎么样?你试过移除并仅设置你需要的这个z吗?我明天会检查你的代码,现在我不能。 - user7776077
是的,基本上我已经尝试了所有关于z-index的东西,就我所知。不过我对Web编码还很陌生。 - mato
1个回答

16
以下方法适用于我:
HTML
<body>
  <div id="map"></div>
  <button id="refreshButton">Refresh Button</button>
</body>

CSS

:层叠样式表
#refreshButton {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 10px;
  z-index: 400;
}

这里有一个包含上述代码的JSBin

地图顶部的刷新按钮

以上截图来自上面链接的JSBin。

我还发现了这个关于在leaflet中创建自定义控制按钮的资源

更新

我将您的HTML更改为以下内容:

<div id="mainContainer">
  <div id="mapDiv">
    <div id="map">
      <button id="refreshButton">
        Button
      </button>
    </div>
  </div>
  <div id="bars"></div>
</div>

我还将#refreshButton的定位规则改为absolute并将其z-index设置为500。

除此之外,我还添加了

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

请查看此JSBin中已更新的解决方案。


是的,我尝试了绝对定位,但正如你在我的代码中所看到的那样,它的结构就像左侧有地图,右侧有条形图。当我使用绝对定位时,调整浏览器窗口大小会破坏它。或者我不确定如何正确地做这件事 - 即使窗口被调整大小,按钮仍保持在同一位置。 - mato
哦,我明白了。我需要将“position:relative”设置为祖先div。我真是太傻了。 - mato
好的,干得好!我也刚刚更新了我的答案,使用了你在问题中指定的HTML。 - Iavor
你最终将哪个祖先 div 元素赋予了 relative 定位? - Iavor
mapDiv。我移除了那个leaflet类。 - mato
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接