今天在慕课网看Bootstrap中的下拉菜单,测试代码的时候遇到了JS实现的下拉菜单无法显示的问题,代码如下
DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>下拉菜单title>
<link rel="stylesheet" href="styles/Bootstraps/bootstrap.css">
head>
<body>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
下拉菜单
<span class="caret">span>
button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项a>li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项a>li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项a>li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项a>li>
ul>
div>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown">
选择你喜欢的水果
<span class="caret">span>
button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu2">
<li role="presentation">
<a role="menuitem" tabindex="-1" href="#">苹果a>
<a role="menuitem" tabindex="-1" href="#">梨a>
<a role="menuitem" tabindex="-1" href="#">香蕉a>
<a role="menuitem" tabindex="-1" href="#">桃a>
li>
ul>
div>
<script src="scripts/jquery-3.3.1.js">script>
<script src="scripts/Bootstraps/bootstrap.js">script>
body>
html>
关于jquery和Bootstrap用了本地导入,也注意了先导入jq的顺序,并没有发现问题,但下拉列表无法显示,使用浏览器的调试窗口查看,有以下报错
查了一下,也没有见到类似问题的具体解释,不过勉强解决了问题,方法如下
提示很明显,需要Popper.js,那么这是什么东西呢,来看一下
### Popper.js
This is the engine, the library that computes and, optionally, applies the styles to
the poppers.
Some of the key points are:
- Position elements keeping them in their original DOM context (doesn't mess with your DOM!);
- Allows to export the computed informations to integrate with React and other view libraries;
- Supports Shadow DOM elements;
- Completely customizable thanks to the modifiers based structure;
Visit our [project page](https://fezvrasta.github.io/popper.js) to see a lot of examples of what you can do with Popper.js!
Find [the documentation here](/docs/_includes/popper-documentation.md).
这是从已经下载好的popper包下载下来的
| Source | |
|:-------|:---------------------------------------------------------------------------------|
| npm | `npm install popper.js --save` |
| yarn | `yarn add popper.js` |
| NuGet | `PM> Install-Package popper.js` |
| Bower | `bower install popper.js --save` |
| unpkg | [`https://unpkg.com/popper.js`](https://unpkg.com/popper.js) |
| cdnjs | [`https://cdnjs.com/libraries/popper.js`](https://cdnjs.com/libraries/popper.js) |
推荐通过npm指令进行下载工程目录,之后在目录下找到Popper.js文件夹,可以看到里面的文件
这里就有一些问题了,如图有popper.js文件,esm和umd文件夹里也有popper.js文件,我并不理解这三个文件的用处以及区别,在别的博客上有人使用三个文件全部调用,可以解决,经尝试确实可以,但显然不合理。经过排除,我们应当只调入umd文件夹中的popper.js文件,且同样需要在Bootstrap文件之前调入,经测试可以解决。
但在bootstrap的文档中我只看到需要注意jq的引入,并没有提及popper文件的调入,暂时也还不理解poppe包的用处,希望可以随着学习逐渐解决这些问题