如何使用CSS和JavaScript创建下拉菜单

In this tutorial you will learn how to create a simple dropdown menu with vanilla Javascript, HTML and CSS. We will walk through the HTML, CSS and Javascript code, but paying more attention to the programming, since this is a JS tutorial. We’ll use just plain JS and CSS, with no frameworks or preprocessors. The only (kind-of) exception will be importing the Font Awesome CSS file because we’ll use one of its icons.

在本教程中,您将学习如何使用香草Javascript,HTML和CSS创建一个简单的下拉菜单。 我们将逐步介绍HTML,CSS和Javascript代码,但会更加关注编程,因为这是JS教程。 我们将只使用普通的JS和CSS,而没有框架或预处理器。 唯一(有点)例外是导入Font Awesome CSS文件,因为我们将使用其图标之一。

This is targeted to developers that have an average understanding of HTML, CSS and JS. I tried to make it as clean as possible, but I won’t focus too much on details here. I hope you all enjoy.

这是针对对HTML,CSS和JS有基本了解的开发人员的。 我试图使其尽可能干净,但在此我不会过多地关注细节。 希望大家喜欢。

屏幕截图 (Screenshots)

This is how the code result looks like:

代码结果如下所示:

Initial screen:

初始屏幕:

Dropdown opened:

下拉列表已打开:

Dropdown with option selected:

选择了选项的下拉列表:

HTML: (HTML:)

In this section, we will discuss the implementation of the HTML code for the demo page. To start off, let’s see the <head> code

在本节中,我们将讨论演示页面HTML代码的实现。 首先,让我们看一下<head>代码

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Dropdown Example</title>

	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/'-awesome/4.7.0/css/font-awesome.min.css">
	<link rel="stylesheet" href="styles.css">
</head>

This is basically HTML head boilerplate, with the exception of the link tags loading the two CSS stylesheets we will use in this tutorial: the Font Awesome styles, and the styles.css file, where we will define this page’s styles.

这基本上是HTML头样板,除了link标签加载了我们将在本教程中使用的两个CSS样式表之外:Font Awesome样式和styles.css文件,我们将在其中定义此页面的样式。

Then, there’s the rest of the HTML file, the body:

然后,还有HTML文件的其余部分,主体:

<body>
	<div class='dropdown'>
		<div class='title pointerCursor'>Select an option <i class="fa fa-angle-right"></i></div>
		
		<div class='menu pointerCursor hide'>
			<div class='option' id='option1'>Option 1</div>
			<div class='option' id='option2'>Option 2</div>
			<div class='option' id='option3'>Option 3</div>
			<div class='option' id='option4'>Option 4</div>
		</div>

	</div>
	<span id='result'>The result is: </span>
	<script>
	  ...
	</script>
</body>
</html>

This section can be divided into 3 main parts:

本节可分为3个主要部分:

  • The .dropdown div, where the dropdown element’s structure will be defined.

    .dropdown div,将在其中定义dropdown元素的结构。

  • The #result element, that will contain the selected option by the user, from the dropdown element.

    #result元素将包含用户从下拉列表中选择的选项。

  • The script written into the <script> tag. Its implementation is hidden here, because its details will be explained in the last section of this tutorial.

    将脚本写入<script>标记。 它的实现在此隐藏,因为其详细信息将在本教程的最后一部分中进行说明。

The dropdown element is a div containing a title and menu elements. The former just defines what text will be presented on the element before any option is selected and the latter will define the options that will be selectable by the element.

下拉元素是一个包含titlemenu元素的div 。 前者只是定义在选择任何选项之前元素上将显示什么文本,后者将定义元素可以选择的选项。

The result element is there just to show you what option is currently selected.

这里的result元素只是向您显示当前选择的选项。

样式: (Styles:)

Below you can check the full css code out. As you can see it makes use of CSS3 transition and transform constructs.

您可以在下面查看完整CSS代码。 如您所见,它利用了CSS3 transitiontransform结构。

Please pay attention to the .dropdown classes definitions. These are used to define the layout for the dropdown container component as well as its inner elements, such as the .title and its .option‘s.

请注意.dropdown类的定义。 这些用于定义下拉容器组件及其内部元素(如.title.option )的.option

body{
	font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

.hide {
    max-height: 0 !important;
}

.dropdown{
	border: 0.1em solid black;
	width: 10em;
	margin-bottom: 1em;
}

.dropdown .title{
	margin: .3em .3em .3em .3em;	
	width: 100%;
}

.dropdown .title .fa-angle-right{
	float: right;
	margin-right: .7em;
	transition: transform .3s;
}

.dropdown .menu{
	transition: max-height .5s ease-out;
	max-height: 20em;
	overflow: hidden;
}

.dropdown .menu .option{
	margin: .3em .3em .3em .3em;
	margin-top: 0.3em;
}

.dropdown .menu .option:hover{
	background: rgba(0,0,0,0.2);
}

.pointerCursor:hover{
	cursor: pointer;
}

.rotate-90{
	transform: rotate(90deg);
}
JavaScript: (JavaScript:)

Now we’ll see how the Javascript part is implemented. We’ll first go through the function definitions and then the code that calls these functions to make the dropdown actions happen.

现在,我们将了解如何实现Javascript部分。 我们将首先遍历函数定义,然后是调用这些函数以执行下拉操作的代码。

Basically, there are 3 actions that take place depending on what the user interaction is, as their listeners are added to the DOM elements:

基本上,根据用户交互的方式,会发生3种操作,因为它们的侦听器已添加到DOM元素中:

  1. Clicking on the dropdown element

    单击下拉元素
  2. Selecting one of the dropdown options

    选择一个下拉选项
  3. Changing the currently selected option

    更改当前选择的选项

I’d like to make it clear that we are using arrow functions( () => {} ) and the const keyword, which are ES6 features. You’re probably good if you’re using a recent version of your browser, but keep that in mind.

我想明确地说,我们使用的是ES6功能箭头函数( () => {} )和const关键字。 如果您使用的是最新版本的浏览器,可能会很好,但请记住这一点。

1.单击下拉元素 (1. Clicking on the dropdown element)
function toggleClass(elem,className){
	if (elem.className.indexOf(className) !== -1){
		elem.className = elem.className.replace(className,'');
	}
	else{
		elem.className = elem.className.replace(/\s+/g,' ') + 	' ' + className;
	}
	
	return elem;
}

function toggleDisplay(elem){
	const curDisplayStyle = elem.style.display;			
				
	if (curDisplayStyle === 'none' || curDisplayStyle === ''){
		elem.style.display = 'block';
	}
	else{
		elem.style.display = 'none';
	}
}


function toggleMenuDisplay(e){
	const dropdown = e.currentTarget.parentNode;
	const menu = dropdown.querySelector('.menu');
	const icon = dropdown.querySelector('.fa-angle-right');

	toggleClass(menu,'hide');
	toggleClass(icon,'rotate-90');
}

When the dropdown element is clicked, it opens(if it is closed) or closes(if it is opened). This happens by binding toggleMenuDisplay to the click event listener on the dropdown element. This function toggles the display of its menu element by the use of the toggleDisplay and toggleClass functions.

单击下拉列表元素时,它会打开(如果已关闭)或关闭(如果已打开)。 这是通过将toggleMenuDisplay绑定到dropdown元素上的click事件侦听器而发生的。 此函数通过使用toggleDisplaytoggleClass函数来切换其menu元素的显示。

2.选择一个下拉选项 (2. Selecting one of the dropdown options)
function handleOptionSelected(e){
	toggleClass(e.target.parentNode, 'hide');			

	const id = e.target.id;
	const newValue = e.target.textContent + ' ';
	const titleElem = document.querySelector('.dropdown .title');
	const icon = document.querySelector('.dropdown .title .fa');


	titleElem.textContent = newValue;
	titleElem.appendChild(icon);
	
	//trigger custom event
	document.querySelector('.dropdown .title').dispatchEvent(new Event('change'));
	//setTimeout is used so transition is properly shown
	setTimeout(() => toggleClass(icon,'rotate-90',0));
}
3.更改当前选择的选项 (3. Changing the currently selected option)
function handleTitleChange(e){
	const result = document.getElementById('result');

	result.innerHTML = 'The result is: ' + e.target.textContent;
}

The function handleTitleChange is bound to the custom change event on the .title element, to change the #result element content whenever the title element changes. This event’s triggering is done on the previous section.

handleTitleChange函数绑定到.title元素上的自定义change事件,以在title元素发生更改时更改#result元素的内容。 该事件的触发已在上一节中完成。

主要代号 (Main code)
//get elements
const dropdownTitle = document.querySelector('.dropdown .title');
const dropdownOptions = document.querySelectorAll('.dropdown .option');

//bind listeners to these elements
dropdownTitle.addEventListener('click', toggleMenuDisplay);
dropdownOptions.forEach(option => option.addEventListener('click',handleOptionSelected));
document.querySelector('.dropdown .title').addEventListener('change',handleTitleChange);

In the main section there’s just some simple code to get the dropdown’s title and options elements to bind to them the events discussed on the last section.

在主要部分中,只有一些简单的代码可以获取下拉菜单的title和options元素,以将上一部分中讨论的事件绑定到它们。

演示版 (Demo)

This application’s full code and demo can be found here.

可以在此处找到该应用程序的完整代码和演示。

更多信息 (More Information)

翻译自: https://www.freecodecamp.org/news/how-to-create-a-dropdown-menu-with-css-and-javascript/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值