gpt4 book ai didi

javascript - 单击屏幕关闭 Canvas 菜单

转载 作者:行者123 更新时间:2023-11-29 16:30:27 25 4
gpt4 key购买 nike

我使用的 Canvas 菜单类似于 W3 Schools 上的菜单,通过调用两个函数来使用 onclick 打开/关闭菜单。我想添加一个功能,以便能够通过单击屏幕上的任意位置来关闭菜单。我是 Javascript 的新手,不知道如何实现它。任何帮助都会很棒!谢谢!

function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}

function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft= "0";
document.body.style.backgroundColor = "white";
}
body {
font-family: "Lato", sans-serif;
transition: background-color .5s;
}

.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}

.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s;
}

.sidenav a:hover {
color: #f1f1f1;
}

.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}

#main {
transition: margin-left .5s;
padding: 16px;
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
<body>

<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>

<div id="main">
<h2>Sidenav Push Example</h2>
<p>Click on the element below to open the side navigation menu, and push this content to the right. Notice that we add a black see-through background-color to body when the sidenav is opened.</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>
</div>
</body>

最佳答案

正如 Matt U 所建议的,您需要通过在 html 中添加此元素来调用 closeNav 点击您的 ma​​in 元素:

...
<div id="main" onclick="closeNav()">
...

但您还需要阻止点击传播(事件冒泡),因为如果不这样做,当您尝试通过点击按钮打开菜单时,点击会冒泡到主 div 并立即关闭菜单...

所以你需要将这些行添加到你的 javascript

document.getElementById("button")
.addEventListener("click", event => {
event.stopPropagation();
}
)

和按钮的ID

 <span id="button" ...

这是一个工作示例 https://codepen.io/gui3/pen/mddogVj?editors=1010

关于javascript - 单击屏幕关闭 Canvas 菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58979200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com