Home > Web Front-end > JS Tutorial > Create a mobile-friendly WordPress hamburger menu

Create a mobile-friendly WordPress hamburger menu

WBOY
Release: 2023-08-28 20:21:07
Original
1106 people have browsed it

创建适合移动设备的 WordPress 汉堡菜单
What you will create

If you want your website to be responsive (and who doesn’t?), it’s important to make sure your main navigation menu works well on small screens.

Large navigation menus can take up too much space on your phone, or even if they don't take up too much space, they can be too small to read or reliably click the correct link.

Hamburger menu is one way to solve this problem. This is a hidden menu until the user clicks on it. It is called the hamburger menu because the symbol representing it is three horizontal lines above and below, which looks a bit like a hamburger.

There are plugins that can turn your main navigation menu into a hamburger menu in WordPress (including the one on Code Canyon), but what if you want to code it into your own theme?

In this tutorial you will learn how to do it.

What do you need

To follow this tutorial you will need:

  • Development installation of WordPress
  • Code Editor
  • Editable themes (if you use a third-party theme, you need to create a child theme)

Start Menu

The code we will write will apply to the menus that WordPress generates using the navigation menu system. You don't need to write new or different menus for mobile devices. (This is one of my pet peeves when a website has different navigation on desktop and mobile, as it usually hurts the user experience on mobile.)

I'll demonstrate this technique with reference to a menu from my own website, adding the code to the header.php file along with the stylesheet and new JavaScript file.

This is the menu on the desktop:

创建适合移动设备的 WordPress 汉堡菜单

This is a horizontal menu located below the banner image and title and above the content.

On mobile devices, the banner image is not visible. I want to remove the menu and replace it with a hamburger symbol. When the user clicks on the symbol, a menu will appear.

This is the code for the menu:

<nav class="menu main">
	<div class="skip-link screen-reader-text">
        <a href="#content" title="<?php esc_attr_e( 'Skip to content', 'tutsplus' ); ?>">
            <?php _e( 'Skip to content', 'tutsplus' ); ?>
        </a>
    </div>
	<?php wp_nav_menu( array( 
        'container_class' => 'main-nav', 
        'theme_location' => 'primary' 
    ) ); ?>
</nav><!-- .main -->
Copy after login

All content is encapsulated in a div with class .menu.main. There is a skip link for screen readers and then the wp_nav_menu() function which includes 'container_class' => 'main-nav' which adds an extra CSS class The menu itself. We can later use these classes to style menus on mobile devices.

So let’s get started.

Add hamburger symbol

The first step is to encode the hamburger symbol into the header.php file and style it so that it is only visible on mobile devices.

In your header.php file, add this code inside the header element (not inside the navigation):

<a class="toggle-nav" href="#">&#9776;</a>
Copy after login

In my case this means the code for the header and navigation is as follows (note that I have omitted the banner in the code below even though it is in my file):

<div class="header-bg">
    
	<header role="banner">
	
		<hgroup class="site-name three-quarters left">
			<h1 id="site-title" class="one-half-left">
		        <a href="<?php echo home_url( '/' ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a>
			</h1>
			<h2 id="site-description"><?php bloginfo( 'description' ); ?></h2>
		</hgroup>
	
		<div class="right quarter">	
			<a class="toggle-nav" href="#">&#9776;</a>	
		</div> <!-- .one-half right -->
		
	</header><!-- header -->
		
</div><!-- header-bg-->

<!-- full width navigation menu - not on landing page -->
<nav class="menu main">
	<div class="skip-link screen-reader-text">
        <a href="#content" title="<?php esc_attr_e( 'Skip to content', 'compass' ); ?>">
            <?php _e( 'Skip to content', 'twentyten' ); ?>
        </a>
    </div>
	<?php wp_nav_menu( array( 
        'container_class' => 'main-nav', 
        'theme_location' => 'primary' 
    ) ); ?>
</nav><!-- .main -->
Copy after login

So the hamburger symbol (displayed using HTML code) is in the header and the navigation menu is below it.

Now add some styling to the toggle-nav element.

Set the style of the hamburger symbol

First, we need to hide the hamburger symbol on the desktop.

In the stylesheet, add the following to hide the hamburger symbol:

.toggle-nav {
    display: none !important;
}
Copy after login

But you do need to make sure it displays on mobile devices. So add a media query, using whatever max-width you normally use for media queries. this is mine:

@media screen and ( max-width: 580px ) {
    .toggle-nav {
        display: inline-block !important;
    }
}
Copy after login

This will make the hamburger icon visible on smaller screens. I used !important to make sure it won't be overridden by any other link styles in the theme.

Now let's add some extra styling to it. Edit the media query so it looks like this:

@media screen and ( max-width: 580px ) {
    .toggle-nav {
        display: inline-block !important;
        float: right;
        margin: 25px;
        font-size: 2em;
        transition: color linear 0.15s;
	}
		
    a.toggle-nav:link, 
	a.toggle-nav:visited,
	a.toggle-nav:hover, 
	a.toggle-nav:active {
        text-decoration: none;
        color: #fff;
    } 
}
Copy after login

This adds color and size to the icon, and also overrides any styling for links, regardless of their state.

This is what the hamburger icon looks like now on mobile devices:

创建适合移动设备的 WordPress 汉堡菜单

This is the style of the hamburger icon. Now comes the navigation menu.

Set the style of the navigation menu

The navigation menu itself needs to be styled on mobile devices. In your media query, add the following CSS:

.menu.main {
    display: inline-block;
    position: relative;
    background: #fff;
    text-align: left;
}
	
.menu.main ul {
    display: none;
    position: absolute;
    overflow: auto;
    top: 0px;
    right: 0px;
    z-index: 999;
    padding-right: 15px;
    background: #fff;
}
	
.menu.main ul li {
    float: none;
    display: block;
    position: relative;
    top: 0px;
    right: 0px;
    min-width: 200px;
    background: #fff;
    text-align: right;
}
	
.main.menu li:after { 
    content: none; 
}
Copy after login

Here are some key aspects of the code:

  • 它更改主菜单的颜色和位置并使文本左对齐。
  • 它将列表隐藏在菜单内,以便当用户首次在移动设备上访问该网站时,不会显示菜单。
  • 它会更改列表中列表项的浮动和颜色。
  • 它为菜单提供相对定位,为列表提供绝对定位,以便它可以位于页面内容的顶部而不是将其向下推。
  • 它会删除桌面上我的主题中的列表项后面的所有元素。

请注意,您需要对菜单进行的调整可能会有所不同,并且取决于它在桌面上的样式。重要的部分是隐藏菜单和定位。

添加 JavaScript

为了让这一切正常工作,我们需要添加一些 JavaScript。当用户点击汉堡图标时,这将使菜单向下滑动。

将一个名为 burger-menu.js 的新文件添加到您的主题中(我喜欢将我的文件放在 scripts 文件夹中)。

将此脚本添加到其中:

jQuery(document).ready(function() {
    jQuery('.toggle-nav').click(function(e) {
        jQuery('.menu.main ul').slideToggle(500);
 
        e.preventDefault();
    });
    
});
Copy after login

当用户单击 .toggle-nav 元素(即汉堡图标)。保存文件并关闭它。

但是除非您将脚本排入队列,否则它将无法工作。打开主题的 functions.php 文件并添加以下内容:

function tutsplus_burger_menu_scripts() {
    
	wp_enqueue_script( 'burger-menu-script', get_stylesheet_directory_uri() . '/scripts/burger-menu.js', array( 'jquery' ) );
 
}
add_action( 'wp_enqueue_scripts', 'tutsplus_burger_menu_scripts' );
Copy after login

这会将您的脚本排入队列,使其正常工作。保存并关闭您的函数文件。

现在,如果您在移动设备上(或在启用响应模式的桌面浏览器中)访问您的网站并单击该汉堡,菜单将会向下滑动。

创建适合移动设备的 WordPress 汉堡菜单

它位于内容之上,而不是将其向下推,并且它以由 JavaScript 驱动的漂亮滑动动作出现。这正是我们想要的。

汉堡菜单将增强移动访问者的用户体验

笨重的桌面优先导航菜单会在小屏幕上占用太多空间,并使人们无法阅读他们访问您网站的内容。

但您不想阻止移动访问者访问与桌面访问者相同的导航。

通过添加这样的汉堡菜单,您可以两全其美:干净的移动布局,可以访问与桌面上相同的导航。

有关 WordPress 菜单的其他帖子

要了解有关 WordPress 菜单的更多信息,请查看我们的其他一些帖子:

The above is the detailed content of Create a mobile-friendly WordPress hamburger menu. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template