前端新手,我正在使用侧边栏的jQuery下拉菜单。
问题是当用户加载页面时菜单已经被删除。
如何更改此设置,以便在加载页面时不会自动下拉? (当我点击不同的页面时,我得到一个打开/关闭效果,例如,当我点击某个地方时它向后缩回然后当页面加载它再次下降时)
此外,当关闭掉落并重新打开它时,POPS会回到屏幕顶部,无论如何都要将其更改为?
的jQuery
<script type="text/javascript">
// Dropdown toggle
$('.dropdown-toggle').click(function(){
$(this).next('.dropdown').toggle();
});
$(document).click(function(e) {
var target = e.target;
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').hide();
}
});
</script>
HTML
<a style="text-decoration:none" class="dropdown-toggle" href="#" title="">2014</a>
<ul class="dropdown">
<li style="list-style-type: none"><a href="#">December 2014</a></li>
</ul>
答案 0 :(得分:0)
您只需要添加CSS
.dropdown {
display:none;
}
这样,在打开页面时关闭它,点击2014
链接就会显示它。单击文档上的任何其他位置将再次关闭它。 http://jsfiddle.net/VPJC2/1/
<强>更新强>
为了防止页面滚动到顶部(因为href="#"
它正在尝试查找不存在的锚点),您可以通过阻止click事件的默认值来修改您的javascript。
//... Other code here
$('.dropdown-toggle').click(function (event) {
event.preventDefault();
$(this).next('.dropdown').toggle();
});
//... Other code here
更新了小提琴:http://jsfiddle.net/VPJC2/1/
答案 1 :(得分:0)
您可以通过添加样式标记来隐藏子菜单,也可以在文档加载时隐藏子菜单。
<强>的JavaScript 强>
<script type="text/javascript">
// Dropdown toggle
$('.dropdown-toggle').click(function(){
$(this).next('.dropdown').toggle();
});
$(document).click(function(e) {
var target = e.target;
if (!$(target).is('.dropdown-toggle') && !$(target).parents().is('.dropdown-toggle')) {
$('.dropdown').hide();
}
});
$(document).ready(function() {
$('.dropdown-toggle').next('.dropdown').toggle();
});
</script>
您也可以使用样式标记(如
)手动隐藏子菜单<强> HTML 强>
<a style="text-decoration:none" class="dropdown-toggle" href="#" title="">2014</a>
<ul class="dropdown" style="display: none;">
<li style="list-style-type: none"><a href="#">December 2014</a></li>
</ul>
您正在使用.click()处理程序。它不会发起点击事件(http://api.jquery.com/click/)
编辑:更正了我的HTML