英文:
javascript selector problem with tilde how to make it a vairable
问题
在JavaScript中,你可以使用以下代码来实现点击链接时关闭移动版本的汉堡菜单:
const sideMenu = document.getElementById('side-menu');
const nav = document.querySelector('.nav');
nav.addEventListener('click', (event) => {
if (event.target.tagName === 'A') {
sideMenu.checked = false;
// 可以根据需要添加其他关闭菜单的逻辑
}
});
这段JavaScript代码会监听导航菜单(.nav
)上的点击事件,如果点击的元素是链接(<a>
标签),它将关闭移动版本的汉堡菜单(将 side-menu
的 checked
属性设置为 false
)。
这样,在点击链接时,汉堡菜单应该会关闭。希望这对你有所帮助。
英文:
I would like to know if it's possible et get this element in Javascript :
.side-menu:checked ~ nav
I've a burger menu using this selector to open it on mobile version, i try to close that menu when a link of it is clicked
my code :
<header class="header">
<a href="#" class="logo"><img src="assets/img/brand.png" alt=""></a>
<input class="side-menu" type="checkbox" id="side-menu" />
<label class="hamb" for="side-menu"><span class="hamb-line"></span></label>
<nav class="nav">
<ul class="menu">
<li><a href="#">Accueil</a></li>
<li><a href="#">Agenda</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
and the css file :
.side-menu {
display: none;
}
/* Toggle menu icon */
.side-menu:checked ~ nav{
max-height: 100%;
}
Any ideas ? I'm trying to change the max value to 0 checking the checkbox value but i have no idea how to do this. There is maybe a other solution using only css but as a beginner i haven't find it
Thxs a lot
答案1
得分: 1
你需要使用querySelector在你的DOM元素上切换一个类。
切换时,CSS类将在你的属性上激活/取消激活,并应用/移除CSS效果。
var side-menu = document.querySelector('.side-menu') // 使用类
side-menu.classList.toggle('open-menu');
和CSS:
.open-menu{
display: block;
max-height: 100%;
min-width: 20%;
}
你可以在这里查看文档1。
英文:
You need to toggle a class on your DOM element using querySelector.
When toggle, the CSS class gonna be active/inactive on your property and apply/remove the CSS effects.
var side-menu = document.querySelector('.side-menu') // Using class
side-menu.classList.toggle('open-menu');
and CSS:
.open-menu{
display: block;
max-height: 100%;
min-width: 20%;
}
You can check the docs right here.
答案2
得分: 0
以下是翻译好的部分:
终于,这个简单的函数在我的链接上起作用了:
function closeM() {
const someCheckbox = document.getElementById('side-menu');
someCheckbox.checked = false;
}
谢谢你让我思考我的问题。
英文:
Finally it's work with this simple function on my links :
function closeM() {
const someCheckbox = document.getElementById('side-menu');
someCheckbox.checked = false;
}
Thanks you make me think on my problem
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论