Viv*_*vek 4 javascript highcharts
我有一个上下文菜单,单击该网络图中的任何节点都会打开该菜单。我正在尝试使用 Javascript 单击外部任意位置时关闭上下文菜单。
我尝试使用 document.onclick" 隐藏它,但它不起作用。
请参阅 jsfiddle 链接以获取代码片段。
单击外部时应关闭上下文菜单。
<div id="contextMenuId" style="display: none" class="contextMenu">
<div id="contextMenuItem1" class="sublot">menu1</div>
<div id="contextMenuItem2">menu2</div>
</div>
plotOptions: {
series: {
cursor: 'pointer',
events: {
click: function (event) {
let contextMenu = document.getElementById('contextMenuId');
contextMenu.onclick = function() {
contextMenu.classList.add("contextMenu");
}
/* document.onclick = function() {
contextMenu.style.display = 'none';
} */
contextMenu.setAttribute('style', 'top: ' + event.pageY + 'px; left:'
+ event.pageX + 'px;');
}
}
},
networkgraph: {
keys: ['from', 'to'],
layoutAlgorithm: {
enableSimulation: true,
friction: -0.9
}
}
},
Run Code Online (Sandbox Code Playgroud)
向文档添加一个单击侦听器,并尝试检查它是在容器元素内部还是外部单击。如果在内部单击,最接近的方法将返回父容器(它将为您提供容器元素),否则如果在外部单击,它将返回 null。我们对 null 感兴趣(在外部单击)然后我们将隐藏上下文菜单 div
document.addEventListener('click', function(e){
let inside = (e.target.closest('#container'));
if(!inside){
let contextMenu = document.getElementById('contextMenuId');
contextMenu.setAttribute('style', 'display:none');
}
});
Run Code Online (Sandbox Code Playgroud)
如果您需要设置除此之外的边界,只需替换#container为任何合适的边界即可。
如果您不使用 jQuery,很少有浏览器还不支持最接近的功能,请确保使用 pollyfill 来实现最接近的功能https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
更新了小提琴https://jsfiddle.net/28tvp30b/
注意:您的容器元素几乎占据了整个页面,很难在容器之外单击。检查您是否确实单击了容器元素外部。
| 归档时间: |
|
| 查看次数: |
3351 次 |
| 最近记录: |