我的site有一个javascript菜单,在加载页面之前加载,需要帮助以防止菜单显示,除非点击。 包含菜单的标题代码为:
<header>
<div class="logo">
<a href="index.html"><img src="images/logo.png" alt=""/></a>
</div>
<div class="button" id="show">
<a href="#">Menu <span>+</span> <span style="display:none;">-</span></a>
</div>
<div class="clear"></div>
<nav class="vertical menu">
<ul>
<li class="current_page_item0"><a href="docs/home.html">Home</a></li>
<li><a href="docs/mon.html">Monday</a></li>
<li><a href="docs/tue.html">Tuesday</a></li>
<li><a href="docs/wed.html">Wednesday</a></li>
<li><a href="docs/thur.html">Thursday</a></li>
<li><a href="docs/fri.html">Friday</a></li>
<li><a href="docs/sat.html">Saturday</a></li>
<li><a href="docs/sun.html">Sunday</a></li>
<li><a href="docs/contact.html">Contact</a></li>
</ul>
</nav>
</header>
启用它的javascript代码是..
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
$('.menu').hide();
$('#show').click(function (){
$(".menu").toggle();
$("span").toggle();
});
</script>
答案 0 :(得分:2)
菜单渲染速度快于脚本执行速度。您需要隐藏CSS中的菜单,因此它将保持隐藏,直到您的脚本将附加事件侦听器。
以下是工作示例。
// Wait for DOM to be ready.
$(function() {
// Keep elements in variables to avoid unnecessary $() calls.
var $menu = $('.menu'),
$flag = $('span');
// Attach event listener.
$('#show').on('click', function() {
$menu.toggle();
$flag.toggle();
});
});
/* Hide menu on page load. */
.menu {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<header>
<div class="logo">
<a href="index.html">
<img src="images/logo.png" alt="" />
</a>
</div>
<div class="button" id="show">
<a href="#">Menu <span>+</span> <span style="display:none;">-</span></a>
</div>
<div class="clear"></div>
<nav class="vertical menu">
<ul>
<li class="current_page_item0"><a href="docs/home.html">Home</a>
</li>
<li><a href="docs/mon.html">Monday</a>
</li>
<li><a href="docs/tue.html">Tuesday</a>
</li>
<li><a href="docs/wed.html">Wednesday</a>
</li>
<li><a href="docs/thur.html">Thursday</a>
</li>
<li><a href="docs/fri.html">Friday</a>
</li>
<li><a href="docs/sat.html">Saturday</a>
</li>
<li><a href="docs/sun.html">Sunday</a>
</li>
<li><a href="docs/contact.html">Contact</a>
</li>
</ul>
</nav>
</header>
答案 1 :(得分:2)
而不是使用JQuery隐藏它们使用CSS
.menu {
display:none;
}
然后你可以做任何你以前做过的事情
$('#show').click(function (){
$(".menu").toggle();
$("span").toggle();
});