为什么slideToggle不能在这里工作?

时间:2014-08-24 05:50:02

标签: javascript jquery css

我一直在努力解决这个问题,我的智慧结束了。有人知道为什么这不起作用(即导航没有弹出)

HTML

<ul id="nav">
    <li><a href="item1.html">item1</a></li>
    <li><a href="item2.html">item2</a></li>
</ul>
<div id="menu">
    <div id="menu-button"><span id="menu-text">Menu</span> <img src="image/nav.png"></div>
</div>

CSS(看起来有点奇怪,我正在进行响应式设计)

#menu {
    position: relative;
    display: block;
    width: 100%;
    height: 50px;
    background-color: #1F5865;
}

#menu-button {
    position: relative;
    width: 100%;
}

#menu-text {
    position: absolute;
    top: 13px;
    left: 15px;
    font-size: 18px;
    font-weight: bold;
    padding-right: 10px;
}

#menu-button img {
    position: absolute;
    right: 15px;
    top: 10px;
}

#nav {
    display: none;
    position: relative;
    width: 100%;
    list-style-type: none;
    padding: 0px;
    margin: 0px;
    font-family: Raleway, Arial, sans-serif;
}

#nav li {
    list-style-type: none;
    text-align: center;
    background-color: #297585;
    padding: 0px;
    width: 100%;
}

#nav a {
    display: block;
    padding: 14px 0px; 
    border-bottom: 1px solid #1F5865;
    color: #FFF;
    width: 100%;
    text-decoration: none;
}

JavaScript(位于<head>标记内)

<script src="js/jquery-1.10.2.min.js"></script>
<script>
$("#menu").click(function(){
    $("#nav").slideToggle();
});
</script>

2 个答案:

答案 0 :(得分:2)

1)使用#来引用ID
2)你需要等到对象可用

Live Demo using HEAD and not onload

<script src="js/jquery-1.10.2.min.js"></script>
<script>
$(function() { // when document is ready    
  $("#menu").on("click",function(){
    $("#nav").slideToggle();
  });
});
</script>

答案 1 :(得分:1)

ID选择器应以#开头。阅读有关jQuery selectors

的更多信息
$(document).on('click','#menu',function(){
    $("#nav").slideToggle();
});

Demo