javascript - 如何切换导航栏可见性?
问题描述
我是 javascript 的初学者。我想使用切换方法添加隐藏和显示按钮。这是我的html。
<body>
<header>
<li><a href="#">Mécanique</a>
<ul class="sub-menu">
<li><a href="#">Mécanique du point</a></li>
<li><a href="#">Mécanique du solide</a></li>
</ul>
</li>
</header>
</body>
解决方案
在 StackOverflow 上提问之前,先了解一下事情是如何工作的。我们都还在学习,但是,我们必须自己尝试。
除此之外,这里是如何通过单击包含“Mécanique”字样的标签jQuery
来隐藏/显示的方法,我会给它一个,以便我们稍后可以参考它。.sub-menu
a
ID
JavaScript
// we put everything in the document.ready handler to ensure that the document has finished loading.
$(document).ready(function() {
// reference the 'a' tag that I gave it an id of 'trigger', and also referencing the .sub-menu ul.
var trigger = $('#trigger'),
menu = $('.sub-menu');
// adding the event listener to the #trigger to hide/show the .sub-menu ul.
trigger.on('click', function(e) {
// cancel the default behaviour when clicking a link.
e.preventDefault();
// hide/show the menu.
menu.toggle();
});
});
ul.sub-menu {
// by default, let's make the .sub-menu ul hidden.
display: none;
}
<body>
<header>
<li><a href="#" id="trigger">Mécanique</a>
<ul class="sub-menu">
<li><a href="#">Mécanique du point</a></li>
<li><a href="#">Mécanique du solide</a></li>
</ul>
</li>
</header>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</body>
希望我把你推得更远。
推荐阅读
- python - CMake FindPython3 无法在 Windows 上找到解释器
- azure-service-fabric - Service Fabric - 无法进行配置升级以添加或删除节点
- image-processing - 如何为视网膜网络训练准备我的图像和注释?
- sql - SQL:我如何按顺序列出所有前2个订单的客户ID:第一个订单是帽子,第二个订单是太阳镜?
- elasticsearch - 将两个弹性查询合并为 1。如何?
- php - 如何回显增加 PHP 的数组值
- reactjs - 使用 Jest 和 Enzyme 对 AntD 模态进行单元测试
- vim - Vim 中的延迟菜单构建
- vba - 删除传入电子邮件中的文本
- javascript - 在谷歌地图中的异步 JS 之后加载 JS