65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 JQuery 的滑动菜单

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (12投票s)

2008 年 3 月 11 日

CPOL
viewsIcon

107578

downloadIcon

1723

使用 JQuery 的 JavaScript 侧边菜单。

引言

JQuery 是一个快速、简洁的 JavaScript 库,它简化了您遍历 HTML 文档、处理事件、执行动画以及向网页添加 AJAX 交互的方式。JQuery 的设计旨在改变您编写 JavaScript 的方式。

在本文中,我将使用 JQuery 构建一个滑动 JavaScript 菜单。

使用代码

首先,您必须引用 JQuery 库,可以从 这里 下载。然后,您可以像下面的代码一样创建菜单 HTML 页面

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>JQuery Sample Menu</title>
    <link rel="Stylesheet" type="text/css" href="styles/navigation.css" />
    <script type="text/javascript" language="javascript" 
            src="scripts/jquery-1.2.3.js"></script>
    <script type="text/javascript" language="javascript" 
            src="scripts/CustomMenu.js"></script>
</head>
<body>
<h2>This is a sample menu using JQuery</h2>
<h4>Try to click on the clickable items in the menu to see the animation</h4>
<ul class="menu">
    <li>- Parent item with no children</li>
    <li>
    - Item 1 with children
    <ul >
    <li>Nested item 1</li>
    <li>Nested item 2</li>
    </ul>
    </li>
    <li>
    - Item 2 with children
    <ul >
    <li>Nested item 1</li>
    <li>Nested item 2</li>
    <li>Nested item 3</li>
    <li>Nested item 4</li>
    </ul>
    </li>
    <li>
    - Item 3 with children
    <ul>
    <li>Nested item 1</li>
    <li>Nested item 2</li>
    <li>Nested item 3</li></ul>
    </li>
    </ul>
</body>
</html>

现在,开始 JavaScript 的魔法吧!只需使用以下 JavaScript 代码片段

$(function() // Register the menu
      {
// Add the click event handler on the list item with sub list
$('li:has(ul)') 
           .click(function(event){
            if (this == event.target) {
               // Hide all the children of the other lists
               $('li:has(ul)').children().hide('slow'); 
               // Make the animation
               $(this).children().animate({opacity:'toggle',height:'toggle'},'slow'); 
                                      }
                     return false;
                                 }
                   )
            // Change the cusrsor.
           .css({cursor:'pointer'})
           // Hide all the nested lists (on the first tinm only).
           .children().hide();
       }
 );

现在您可以在无需编写大量 JavaScript 代码的情况下获得滑动效果。

菜单初始状态

init.JPG

菜单运行状态

loading.JPG

关注点

JQuery 是一个非常有用的 JavaScript 库,您应该使用它!我很快会发布关于 JQuery 选择器和其他运算符的文章。

希望对您有所帮助。

© . All rights reserved.