简体   繁体   English

为什么我的下拉菜单代码不起作用

[英]Why wont my drop down menu code work

Drop down menu will not work ! 下拉菜单将不起作用! for css I used the "display: none;" 对于CSS,我使用了“显示:无;” to hide the list but Im wondering if this is the most efficient way to perform a drop down menu? 隐藏列表,但我想知道这是否是执行下拉菜单的最有效方法? I used this concept from a codeacademy project. 我在代码学院项目中使用了这个概念。

Im sure there might be some code in here that may make you cringe but please take it easy on me, I'm an absolute rookie at programming! 我确定这里可能会有一些代码会让您感到畏缩,但是请对我放轻松,我是编程的绝对新手! Thank you! 谢谢!

 $(document).ready(function() { $('p').hover(function() { $(this).find('ul').fadeToggle(400); }); }); 
 * { margin: 0; padding: 0; } .main { margin: 0 auto; height: 400px; width: 400px; } .container { max-width: 230px; max-height: 300px; margin: 0 auto; background-color: #024F79; } p { text-align: center; color: #fff; border-bottom: 1px solid #fff; font-size: 18px; padding: 8px; } ul { list-style-type: none; display: none; } ul li { padding: 10px; border-bottom: 1px solid white; color: white; font-size: 18px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <body> <div class="main"> <div class="container"> <p>How do I ?</p> <ul> <li>View my Transcript</li> <li>View my Conformation Page</li> <li>Register for Courses</li> <li>Pay for Courses/Exams</li> </ul> </div> </div> </body> 

$(this).find('ul') will look inside of the p element as a result of using this as the context. 使用this作为上下文的结果, $(this).find('ul')将在p元素内部。 You could use .next() 您可以使用.next()

$(this).next('ul').fadeToggle(400);

However, a better approach would be to restructure your html and wrap the whole p and ul with a div that has an id in order to facilitate the UI fading. 但是,更好的方法是重组html并用具有id的div包裹整个pul ,以便于UI淡化。

<div id="menu">
 <p>How do I ?</p>
 <ul>
  <li>View my Transcript</li>
  <li>View my Conformation Page</li>
  <li>Register for Courses</li>
  <li>Pay for Courses/Exams</li>
 </ul>
</div>

And then use your original code except target the #menu item 然后使用原始代码,但将#menu项作为目标

$('#menu').hover(function() {
 $(this).find('ul').fadeToggle(400);
});

jsFiddle Demo

也许可以使用纯CSS解决方案来代替JavaScript,除非您想制作一些动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM