本文实例为大家分享了JavaScript实现下拉菜单显示隐藏的具体代码,供大家参考,具体内容如下
有时需要这种页面效果:
鼠标移动到元素上面时,实现下拉菜单
鼠标移开元素后,下拉菜单不见了
实现思路
1、一个盒子里包含上下两部分,下面部分为子菜单,先设置为隐藏:display: none;
2、当鼠标移动到盒子上:触发事件- – -onmouseover ,js设置下面部分子菜单的display值为- – -block,使子菜单显示
3、鼠标移开盒子:触发事件- – -onmouseout ,js又设置下面部分子菜单的display值为- – -none,使子菜单又隐藏起来
4、字体颜色,背景颜色等样式的改变,根据所需进行相应变化
代码示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>操作元素-新浪下拉菜单</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } ul li { list-style: none; } a { text-decoration: none; color: #4c4c4c; } a:hover { color: #e88415; } .box { width: 80px; margin: 50px auto; font-size: 14px; color: #4c4c4c; } .weibo { position: relative; background-color: #fcfcfc; } .weibo a { display: block; height: 40px; line-height: 40px; padding-left: 20px; } .change { color: #f9a74f; background-color: #edeef0; } i { position: absolute; top: 50%; right: 15px; margin-top: -4px; width: 5px; height: 5px; border-bottom: 1px solid orangered; border-right: 1px solid orangered; transform: rotate(45deg); } .weiboList { display: none; } .weiboList li a { display: block; width: 80px; height: 33px; line-height: 33px; padding-left: 15px; border-bottom: 1px solid #fecc5b; background-color: #fff; } .weiboList li a:hover { background-color: #fff5da; } </style> </head> <body> <div class="box"> <div class="weibo"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >微博<i class="select"></i></a></div> <ul class="weiboList"> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >私信</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >评论</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >@我</a></li> </ul> </div> <script> var box = document.querySelector('.box'); var weibo = document.querySelector('.weibo'); var weiboList = document.querySelector('.weiboList'); box.onmouseover = function() { weibo.className = 'weibo change' weiboList.style.display = 'block'; } box.onmouseout = function() { weibo.className = 'weibo'; weiboList.style.display = 'none'; } </script> </body> </html>
页面效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持NICE源码。