今天在慕課網看Bootstrap中的下拉菜單,測試代碼的時候遇到了JS實現的下拉菜單沒法顯示的問題,代碼以下css
<!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的順序,並無發現問題,但下拉列表沒法顯示,使用瀏覽器的調試窗口查看,有如下報錯html
查了一下,也沒有見到相似問題的具體解釋,不過勉強解決了問題,方法以下jquery
提示很明顯,須要Popper.js,那麼這是什麼東西呢,來看一下git
### 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包下載下來的github
| 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文件夾,能夠看到裏面的文件npm
這裏就有一些問題了,如圖有popper.js文件,esm和umd文件夾裏也有popper.js文件,我並不理解這三個文件的用處以及區別,在別的博客上有人使用三個文件所有調用,能夠解決,經嘗試確實能夠,但顯然不合理。通過排除,咱們應當只調入umd文件夾中的popper.js文件,且一樣須要在Bootstrap文件以前調入,經測試能夠解決。bootstrap
但在bootstrap的文檔中我只看到須要注意jq的引入,並無說起popper文件的調入,暫時也還不理解poppe包的用處,但願能夠隨着學習逐漸解決這些問題瀏覽器