首页 > 解决方案 > 通过 eventListener 打开/关闭传单图例

问题描述

在导航栏中单击“图例”时,我正在尝试进行开/关切换。但是,当我为 构造函数时addEventListener,我不断收到类型错误。我知道这是因为info未定义,但我不确定如何定义它,因此style display可以更改为,当在导航栏中单击block时它会出现在地图上。Legend

有什么建议可以为我指明正确的方向吗?

HTML:

<!--Navbar-->
    <nav class="navbar">
        <div class="logo">
            <h4> Earthquake Feed</h4>
        </div>
        <ul class="nav-links">
            <li><a href="#simpleModal" id="aboutModal">About</a></li>
            <li><a href="#legend" id="legend">Legend</a></li>
        </ul>
    </nav>

CSS:

/*CSS for legend*/
.info {
  padding: 6px 8px;
  font: 14px/16px Arial, Helvetica, sans-serif;
  background: white;
  background: rgba(255,255,255,0.8);
  box-shadow: 0 0 15px rgba(0,0,0,0.2);
  border-radius: 5px;
  display: none;
  }

.legend {
  background-color: “black”;
  line-height: 26px;
  color: #555;
  width: auto;

Javascript:

// adds legend to map
var legend = L.control({position: 'bottomright'});

legend.onAdd = function(map) {
    var div = L.DomUtil.create('div', 'info legend'),
        magnitudes = [0,1,2,3,4,5];

    div.innerHTML += "<h4 style='margin:5px'>Magnitude</h4>" 
    div.innerHTML += '<i class="circleR" style=background:>' + '</i>' + "Recent" + '<br>'

    // loop through color intervals and generate a lable
    for (var i=0; i < magnitudes.length; i++) {
        div.innerHTML += 
                        '<i class="circle" style=background:' + getColor(magnitudes[i] + 1) + '></i>' +
                        magnitudes[i] + (magnitudes[i+1]?'&ndash;' + magnitudes[i+1] + '<br>': '+');
    }
    return div;
};
legend.addTo(map);

// toggles legend on and off
var legendLink = document.getElementById("legend");
legendLink.addEventListener('click', openLegend);
function openLegend(){
    info.style.display = 'block';
}

标签: javascriptfunctionleafletevent-listener

解决方案


您需要一个 DOM 元素来指定要设置样式的元素。

function openLegend(){
    document.getElementByClass("legend").style.display = 'block';
}

应该为你工作。


推荐阅读