Blogger Information
Blog 6
fans 0
comment 0
visits 3649
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
下拉菜单之绝对定位和事件监听
Dobeen
Original
784 people have browsed it

预览效果

HTML主体代码

  1. <ul id="nav">
  2. <li><a href="#">首页</a></li>
  3. <li>
  4. <a href="#">技术文章</a>
  5. <ul>
  6. <li><a href="#">PHP</a></li>
  7. <li><a href="#">JavaScript</a></li>
  8. <li><a href="#">Python</a></li>
  9. <li><a href="#">Linux</a></li>
  10. </ul>
  11. </li>
  12. <li><a href="#">博客</a></li>
  13. <li>
  14. <a href="#">资源下载</a>
  15. <ul>
  16. <li><a href="#">学习工具</a></li>
  17. <li><a href="#">开发环境</a></li>
  18. <li><a href="#">编辑器/IDE</a></li>
  19. <li><a href="#">国外资源</a></li>
  20. </ul>
  21. </li>
  22. <li><a href="#">行业资讯</a></li>
  23. </ul>

CSS样式

  1. * { margin: 0; padding: 0; font-size: 14px; font-family: "Microsoft YaHei UI"; }
  2. li { list-style: none; }
  3. #nav { background: #000; height: 50px; line-height: 50px; }
  4. #nav li { float: left; position: relative; }
  5. #nav a { color: #ddd; padding: 0 20px; text-decoration: none; }
  6. #nav a:hover { color: #FFF; }
  7. #nav li ul { display: none; position: absolute; width: 210px; border: 1px solid #ddd; }
  8. #nav li ul a { color: #000; }

通过子菜单的样式,理解了绝对定位、相对定位的概念。

JavaScript代码

  1. const navs = document.querySelectorAll('#nav li');
  2. navs.forEach(function (nav) {
  3. //为没一个导航菜单li添加事件监听
  4. nav.addEventListener('mouseover', showMenu);
  5. nav.addEventListener('mouseout', closeMenu);
  6. })
  7. function showMenu (event) {
  8. //这里需要判断相邻标签是否是子菜单
  9. if(event.target.nextElementSibling !== null && event.target.nextElementSibling.nodeName == 'UL'){
  10. event.target.nextElementSibling.style.display = 'block';
  11. }
  12. }
  13. function closeMenu (event) {
  14. if(event.target.nodeName == 'A' && event.target.nextElementSibling !== null){
  15. event.target.nextElementSibling.style.display = 'none';
  16. }
  17. }

学习总结和感悟

  1. CSS要多理解,配合控制台查看各个元素及布局区域特征、变化,有助于理解;
  2. JS代码还是得多写,多写几遍才能掌握事件监听、冒泡的原理;
  3. 课后练习和作业还是得坚持。
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:现在学习重点不js上
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post