javascript - 通过 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]?'–' + 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';
}
解决方案
您需要一个 DOM 元素来指定要设置样式的元素。
function openLegend(){
document.getElementByClass("legend").style.display = 'block';
}
应该为你工作。
推荐阅读
- mongodb - 使用动态键累积文档
- java-8 - 在 java 8 中限制和获取平面列表
- spring - 仅为 mongodb 创建 ssl 连接
- google-maps - 在谷歌地图上绘制多边形并查询位于该区域的项目
- rest - 使用 REST Assured 进行 Web 服务测试:在 POST 请求中使用参数时收到失败响应
- c# - unity transform.position 无法正常工作
- c++ - 无法导入 C++ 代码,使用 VS 2015 在 Win32 中使用 StaticLibrary dll 编写,它将 masm 中的键盘输入作为 .lib 和 .dll 文件
- python - ElementTree.findall 不返回
- css - max-width 对表格没有任何作用
- r - 为什么随机森林的性能比决策树差