This tutorial will teach you how to create and animate a hamburger menu icon, and then attach an event listener via jQuery to trigger the dropdown menu.
I will be using Jade (Pug) and Sass instead of plain HTML and CSS. So you should have at least a basic understanding of these template engines.
Create a playground
We will start by implementing a simple playground. I will only provide the Jade template along with the Sass styles as that is outside the scope of this tutorial. You can accept it and use it, or come up with your own design.
Jade File:
body #container #header #body .content .left .right - for (i=1; i <= 5 ; i++ ) div( id="text" + i ) .content .left .right - for (j=6; j <= 10 ; j++ ) div( id="text" + j ) .content .left .right - for (k=11; k <= 15 ; k++ ) div( id="text" + k )
Sass File:
=flex() display: -webkit-box display: -moz-box display: -ms-flexbox display: -webkit-flex display: flex =transition($time) -webkit-transition: all $time ease -moz-transition: all $time ease -ms-transition: all $time ease -o-transition: all $time ease transition: all $time ease html, body margin: 0 padding: 20px 0 +flex() justify-content: center //----------------------------------// #container width: 320px height: 550px background-color: #ebebeb overflow: hidden #header height: 45px background-color: #9b9b9b position: relative #body padding: 0 20px padding-top: 40px +flex() flex-direction: column justify-content: flex-start .content +flex() flex-direction: row justify-content: flex-start margin-bottom: 25px .left width: 100px height: 100px margin-right: 15px background-color: #e1e1e1 .right @for $i from 1 through 15 #text#{$i} margin-top: 10px width: 50 + random(100) + px height: 10px background-color: #e1e1e1
Note: Here I have created two mixins named flex
and transition
. Mixins make it easier to reuse certain CSS rules by grouping them together. Whenever I need to add display:flex
and all the vendor prefixes, I can use flex()
instead, thanks to the mixin.
We will use this structure and build on it for the rest of this tutorial.
The final result should look like this:
View current code
Hamburger menu icon
Now it’s time to create a simple but attractive hamburger menu and animate it via CSS.
Add a new div inside #header
and name it #hamburger
. Then create two child divs inside #hamburger
. They should have a common class and personal ID.
#hamburger .strip#top .strip#bottom
Now we need to use the generic class .strip
to style the parent #hamburger
div and the child div.
#hamburger height: 100% width: 45 +flex() flex-direction: column justify-content: space-between padding-left: 20px
We set the height of the div to the height of its parent div, which is #header
, by defining Height: 100%
. Additionally, we set a width value for this parent div, which will define its "clickable" area.
Next, we add Flexbox with all vendor prefixes using the mixin we created earlier.
Since we want the .strip
div to be positioned vertically, we set flex-direction: column
and then use justify-content: space- Between
so that in .strip
Add spaces between divs.
We then need to push these divs towards each other by adding bottom and top padding to their respective divs.
#top margin-top: 17px #bottom margin-bottom: 17px
We also added padding-left: 20px
to move the .strip
div further to the right.
The next step is to style the strip. It's relatively simple to just define the size and color of the div.
.strip width: 25px height: 2px background-color: #ffffff
The final result with the hamburger menu icon should look like this:
The next step is to animate the menu icon so that when it is clicked, it should animate into a cross symbol.
Hamburger menu icon animation
At this point, we'll use basic jQuery to toggle some CSS classes.
Let's first create the CSS class we want to toggle.
We will make use of CSS's transform
property and the transition
property's translation and rotation settings.
First, add transitions to the #top
and #bottom
divs using mixins with specific timing parameters.
#top margin-top: 17px +transition(.25s) #bottom margin-bottom: 17px +transition(.25s)
Now we need to define the style of the class to be switched.
We will rotate and translate each .strip
div individually, so we need to switch different classes for the #top
and # bottom
divs.
#top margin-top: 17px +transition(.25s) &.topRotate transform-origin: center transform: translateY(4px) rotateZ(45deg) #bottom margin-bottom: 17px +transition(.25s) &.bottomRotate transform-origin: center transform: translateY(-5px) rotateZ(-45deg)
Here we define two different classes of styles named .bottomRotate
and .topRotate
which will be added to or removed from their respective reference divs, #top
and #bottom
.
Please note that different sizes of the .strip
class will result in different translateY
and rotateZ
values being required in order to animate the correct cross sign.
Use jQuery for class switching
We define how each .strip
div is animated when the topRotate
and bottomRotate
classes exist. However, we haven't attached an event listener to toggle these classes.
创建一个新的 JavaScript 文件,并使用以下代码将 topRotate
和 bottomRotate
类切换到带有 #top
和 #bottom
分别是 ID。
$(document).ready(function(){ $("#hamburger").click(function(){ $("#top").toggleClass("topRotate"); $("#bottom").toggleClass("bottomRotate"); }); })
我们将所有代码放入 $(document).ready(function(){})
中,以便在采取任何操作之前等待整个页面加载。
当我们点击 #hamburger
div 时,它将切换具有特定 ID 的 div 的类。
注意:不要忘记将 jQuery 源文件添加到您的项目中。
查看当前代码
创建菜单列表
下一步是创建一个包含列表项的菜单。
在 #header
下使用以下结构:
#dropDown #background ul li Home li Blog li Projects li Authors li Jobs li Contact
因此,我们在这里使用 ul
标签作为父标签,以便将 li
标签作为子标签的项目分组。此外,为了创建展开的背景动画,我们还添加了一个 ID 为 #background
的 div。
让我们首先设置 ul
和 li
元素的样式。
ul list-style: none padding: 0 margin: 0
将 list-style
设置为 none
,以便从 ul
元素中删除项目符号,并同时设置 padding
和 margin
为 0,以便删除所有预定义值。
现在设置 li
元素的样式:
li //display: none background-color: #9b9b9b color: #ffffff font-family: 'Quicksand', sans-serif font-weight: lighter font-size: 15px padding: 20px padding-left: 60px &:after position: absolute content: '' left: 60px width: 60% height: 1px bottom: 4px background: rgba(255, 255, 255, 0.25) &:last-child:after width: 0
这里我注释掉了 display:none
以便能够看到结果。但是,在制作动画时,我们最初将使用它来隐藏列表元素。
我还添加了 after
伪元素并相应地设置了样式,以便用直线分隔每个 li
元素。 :last-child:after
删除最后一个 li
元素的这一行。
查看当前代码
动画菜单列表
现在我们将使用一些 Sass 控制指令,以便向每个 li
元素添加具有不同属性的 CSS 关键帧动画。
@keyframes drop 0% opacity: 0 transform: scale(1.3) 100% opacity: 1 transform: scale(1) @keyframes fold 0% opacity: 1 transform: scale(1) 100% opacity: 0 transform: scale(0.7)
在这里,我们定义了关键帧动画 drop
和 fold
。
drop
用于动画打开菜单列表。初始缩放比例增加了 30%,随着透明度从 0 变为 1,它会缩小到原始大小。相反的操作发生在 fold
中。
p>
现在我们需要将这些关键帧附加到 li
元素。这部分就是 Sass 派上用场的地方。
@for $i from 1 through 6 li:nth-child(#{$i}) animation: name: fold duration: 80ms*(6-$i) + 1ms timing-function: ease-in-out fill-mode: forwards li.anim:nth-child(#{$i}) animation: name: drop duration: 100ms*$i timing-function: ease-in-out fill-mode: forwards
这里我使用了一个从 1 到 6 的 for 循环,索引为 $i
。
现在我们需要使用此索引将每个动画附加到具有不同持续时间的 li
元素。
首先,考虑 li.anim:nth-child(#{$i})
行。
在这里,我们获取 li
元素的 $i
子元素,其类为 anim
。
我们将切换此 anim
类。因此,当将其添加到 li
元素时,名称为 drop
的关键帧动画将采取行动。删除后,fold
动画将采取行动。
下一个重要的事情是 duration
属性。
持续时间:100ms*$i
drop
动画会延长每个递增子编号的动画持续时间。因此,编译此代码时,第一个 li
子级将具有 duration: 100ms
,最后一个子级将具有 duration: 600ms
。
这会给人一种依次为每个元素添加动画的感觉。
我们对 fold
动画执行相同的操作。这次,最后一个元素的动画应该更快,因此 持续时间:80ms*(6-$i) + 1ms
。持续时间增加 1ms 是因为当你将持续时间设置为 0 时,可能会出现一些问题,并且你的动画可能无法正常工作。
当我们设计 li
元素样式时,我提到我们需要使用 display:none
以避免意外的动画播放。如果您不将其设置为 none
,您将看到 fold
动画在页面加载时播放一次。
如果我们将 display
属性设置为 none
,我们将看不到该内容,然后我们需要显示 li
元素,然后切换 anim
类。
我们希望在单击汉堡包图标时播放动画。因此,让我们使用一些 jQuery 将每个 li
项的 display
属性设置为 block
并切换 anim
类.
$(document).ready(function(){ $("#hamburger").click(function(){ $("#top").toggleClass("topRotate"); $("#bottom").toggleClass("bottomRotate"); $("li").show(); $("li").toggleClass("anim"); }); })
查看当前代码
您会注意到,我们可以单独看到每个 li
元素的动画。然而,我们宁愿有一种扩展菜单的感觉。
为了解决这个问题,我们只需扩展 div 的高度即可。该 div 是 #background
,我们最初是在创建 ul
和 li
元素时添加的。
#background width: 100% height: 0 background-color: #9b9b9b position: absolute +transition(.45s) &.expand height: 550px
我们将切换 expand
类,以便将 height
属性设置为 550px
内的 .45s
。请注意,我使用 transition
mixin 来定义具有特定时间参数的转换。
最终结果
结论
在本教程中,我们练习了如何通过 Jade 和 Sass 模板引擎在 HTML 和 CSS 中使用 for 循环。最重要的是,我们创建了 CSS 关键帧动画,并将它们与不同的持续时间属性附加到特定的 HTML 元素。然后我们使用 jQuery 切换类来控制这些动画。
The above is the detailed content of Develop mobile-friendly drop-down menus. For more information, please follow other related articles on the PHP Chinese website!

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools
