Bootstrap 5 – 可扩展但不能折叠导航栏

huangapple go评论50阅读模式
英文:

Bootstrap 5 - Can expand but not collapse navbar

问题

我曾经使用较早版本的Bootstrap,但现在尝试迁移到当前版本5.3.0。我正在使用模板代码,已经更新为当前的Bootstrap版本。

我目前正在尝试让导航栏工作,但只能部分成功;在小屏幕上,我可以展开导航栏,但当我想要收起导航栏时,切换按钮不起作用。我已经仔细查看了代码,但感觉有点看不清问题在哪里。

以下是您提供的代码片段,我已翻译好:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>StrindbergAppen</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 加载外部样式 -->
    <link rel="stylesheet" type="text/css" href="./css/style.css">

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- 加载用于菜单按钮图标的脚本 -->
    <script src="https://unpkg.com/feather-icons"></script>

    <script>
        /* ----- SPA - 单页应用逻辑的JavaScript ----- */
        // 帮助函数,显示具有ID page+p的页面并隐藏所有其他页面
        function showPage(p) {
            // 步骤1 - 隐藏所有页面
            pageArr = document.getElementsByClassName("page");
            for (let i = 0; i < pageArr.length; i++) {
                let page = pageArr[i];
                page.style.display = "none";
            }
            // 步骤2 - 显示所选页面
            document.getElementById("page" + p).style.display = "block";

            // 步骤3 - 使所有导航栏按钮无效
            let btnArr = document.getElementsByClassName("navbar-btn");
            for (let i = 0; i < btnArr.length; i++) {
                let btn = btnArr[i];
                btn.classList.remove("active");
            }

            // 步骤4 - 使具有类别nav+p的导航栏按钮激活
            btnArr = document.getElementsByClassName("nav" + p);
            for (let i = 0; i < btnArr.length; i++) {
                let btn = btnArr[i];
                btn.classList.add("active");
            }
        }
        /* ----- ----- */

        // 初始化函数。在这里,我们可以放置需要初始化原型的代码。
        function initPrototype() {
            // 例如,当使用声音或传感器时,这变得很重要。
            console.log("==> 原型初始化开始。");

            // 显示起始页/着陆页
            showPage(1);
        }
    </script>

</head>

<body onload="showPage(0);">
    <!-- Page0 is needed for initPrototype() function. DON'T REMOVE! -->
    <!-- Page0 is needed for initPrototype() function. DON'T REMOVE! -->
    <div id="page0" class="page">
        <div class="prototype-start-page">
            <button class="btn btn-success" type="button" onclick="initPrototype();">开始原型</button>
        </div>
    </div>
    <!-- Page0 is needed for initPrototype() function. DON'T REMOVE! -->
    <!-- Page0 is needed for initPrototype() function. DON'T REMOVE! -->
    <!-- 所有页面 -->
    <!-- 新页面必须具有类别'page'和ID 'pageX',其中X必须是页面的唯一编号,并具有HTML结构: -->

    <!--
        <div id="pageX" class="page">
            新页面的HTML内容。不要忘记包含菜单。
        </div>
    -->

    <!-- 在示例中,我们有三个原型应用程序的页面,page1、page2和page3,所以下一页自然应该是page4: -->

    <!--
        <div id="page4" class="page">
            新页面的HTML内容。不要忘记包含菜单并添加第4个菜单选项。
        </div>
    -->

    <!-- 为了使处理页面导航的JavaScript正常工作,菜单按钮必须具有类别'navbar-btn'和'navX',其中X是菜单按钮打开的页面的编号。我们还必须通过将'4'作为showPage()函数的参数来指定要打开的页面编号。例如,要添加一个菜单按钮以打开'page4',我们将创建以下按钮: -->

    <!--
        <button class="nav4 nav3 btn navbar-btn btn-primary" type="button" onclick="showPage(4);">转到页面4</button>
    -->

    <!-- 类别navbar__btn--active包含活动菜单选项的样式。 -->
    
    <!-- 页面1 -->
    <div id="page1" class="page">
        <!-- 顶部栏 -->
        <div class="top-app-bar">
            <div>
                <i class="icon-mob-size" data-feather="home" onclick="showPage(1)"></i>
                <span class="top-nav-headline">StrindbergAppen</span>
            </div>
        </div>

        <!-- 导航栏 -->
        <nav class="navbar fixed-bottom navbar-expand-lg navbar-light bg-light">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">Navbar</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse"
                    data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
                    aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link active" aria-current="page" href="#">StrindbergAppen</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">Bilder på August Strindberg</a>
                        </li>

                        <li class="nav-item">
                            <

<details>
<summary>英文:</summary>

I used to work with an earlier version of Bootstrap but am trying to get into the current version 5.3.0. I&#39;m using template code which I&#39;ve updated to current Bootstrap version. 

I&#39;m currently trying to get the navbar working but it only does half-way; In small-screen I can expand the navbar, but the toggler button doesn&#39;t work when I want to collapse the navbar again. I&#39;ve been up and down the code but feel kind of snowblind as I can&#39;t see what&#39;s wrong.

    &lt;!DOCTYPE html&gt;
    &lt;html lang=&quot;en&quot;&gt;
     
    &lt;head&gt;
    	&lt;title&gt;StrindbergAppen&lt;/title&gt;
    	&lt;meta charset=&quot;utf-8&quot;&gt;
    	&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    	&lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt;
    	&lt;!-- Laddar extern styling --&gt;
    	&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;./css/style.css&quot;&gt;
    	
    	&lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt;
    	&lt;script src=&quot;https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js&quot;&gt;&lt;/script&gt;
    	&lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt;
    	
    	&lt;!-- Laddar script f&#246;r att f&#229; tillg&#229;ng till ikoner f&#246;r menyknapparna --&gt;  
    	&lt;script src=&quot;https://unpkg.com/feather-icons&quot;&gt;&lt;/script&gt;
    
    	&lt;script&gt;
    		/* ----- Javascript for SPA - Single Page Application logic ----- */
    		// Help function that shows page with id page+p and hides all other pages
    		function showPage(p) {
    			// Step 1 - Hide all pages
    			pageArr = document.getElementsByClassName(&quot;page&quot;);
    			for (let i = 0; i &lt; pageArr.length; i++) {
    				let page = pageArr[i];
    				page.style.display = &quot;none&quot;;
    			}
    			// Step 2 - Show the selected page
    			document.getElementById(&quot;page&quot; + p).style.display = &quot;block&quot;;
     
    			// Step 3 - Make all navbar buttons inactive 
    			let btnArr = document.getElementsByClassName(&quot;navbar-btn&quot;);
    			for (let i = 0; i &lt; btnArr.length; i++) {
    				let btn = btnArr[i];
    				btn.classList.remove(&quot;active&quot;);
    			}
     
    			// Step 4 - Make page all navbar buttons with class nav+p active
    			btnArr = document.getElementsByClassName(&quot;nav&quot; + p);
    			for (let i = 0; i &lt; btnArr.length; i++) {
    				let btn = btnArr[i];
    				btn.classList.add(&quot;active&quot;);
    			}
    		}
    		/* -----  ----- */
     
    		// Init function. Here we can put code that is needed to initialize our prototype.
    		function initPrototype() {
    			// For example, when using sound or sensors this becomes important.
    			console.log(&quot;==&gt; Prototype init started.&quot;);
     
    			// Show the landingpage/startpage
    			showPage(1);
    		}
    	&lt;/script&gt;
    
    &lt;/head&gt;
     
    &lt;body onload=&quot;showPage(0);&quot;&gt;
    	&lt;!-- Page0 is needed for initPrototype() function. DON&#39;T REMOVE! --&gt;
    	&lt;!-- Page0 is needed for initPrototype() function. DON&#39;T REMOVE! --&gt;
    	&lt;div id=&quot;page0&quot; class=&quot;page&quot;&gt;
    		&lt;div class=&quot;prototype-start-page&quot;&gt;
    			&lt;button class=&quot;btn btn-success&quot; type=&quot;button&quot; onclick=&quot;initPrototype();&quot;&gt;Start prototype&lt;/button&gt;
    		&lt;/div&gt;
    	&lt;/div&gt;
    	&lt;!-- Page0 is needed for initPrototype() function. DON&#39;T REMOVE! --&gt;
    	&lt;!-- Page0 is needed for initPrototype() function. DON&#39;T REMOVE! --&gt;
    	&lt;!-- alla sidor --&gt;
    	&lt;!-- Nya sidor m&#229;ste ha klassen &#39;page&#39; och ett id &#39;pageX&#39;, d&#228;r X m&#229;ste vara ett unikt nummer p&#229; sidan,
    		 och ha HTML-strukturen:
    
    		&lt;div id=&quot;pageX&quot; class=&quot;page&quot;&gt;
    			Nya sidans HTML-inneh&#229;ll. Gl&#246;m inte att ta med menyn.
    		&lt;/div&gt;
    
    		I exemplet har vi tre sidor f&#246;r app-prototypen, page1, page2 och page3, s&#229; en naturlig n&#228;sta sida vore page4:
    
    		&lt;div id=&quot;page4&quot; class=&quot;page&quot;&gt;
    			Nya sidans HTML-inneh&#229;ll. Gl&#246;m inte att ta med menyn och l&#228;gga till ett 4e menyalternativ.
    		&lt;/div&gt;
    
    		F&#246;r att javascriptet som sk&#246;ter sidnavigeringen skall fungera kr&#228;vas att meny-knapparna har klasserna
    		&#39;navbar-btn&#39; och &#39;navX&#39;, d&#228;r X &#228;r nummret f&#246;r sidan som meny-knappen &#246;ppnar. Vi m&#229;ste ocks&#229; ange nummret
    		p&#229; sidan som skall &#246;ppnas av meny-knappen genom att anv&#228;nda &#39;4&#39; som parameter till funktionen &#39;showPage();&#39;
    
    		T ex, f&#246;r att l&#228;gga till en meny-knapp f&#246;r &#39;page4&#39; s&#229; skulle vi skapa f&#246;ljande knapp:
    		&lt;button class=&quot;nav4 nav3 btn navbar-btn btn-primary&quot; type=&quot;button&quot; onclick=&quot;showPage(4);&quot;&gt;Go to page 4&lt;/button&gt;
    
    		Klassen navbar__btn--active inneh&#229;ller stylingen f&#246;r det menyalternativ som &#228;r aktivt.
    	--&gt;
    
    	&lt;div id=&quot;page1&quot; class=&quot;page&quot;&gt;
    		&lt;!-- Top bar --&gt;
    		&lt;div class=&quot;top-app-bar&quot;&gt;
    			&lt;div&gt;
    				&lt;i class=&quot;icon-mob-size&quot; data-feather=&quot;home&quot; onclick=&quot;showPage(1)&quot;&gt;
    				&lt;/i&gt;
    				&lt;span class=&quot;top-nav-headline&quot;&gt;StrindbergAppen&lt;/span&gt;
    			&lt;/div&gt;
    		&lt;/div&gt;
    		
    		&lt;!-- Navbar --&gt;
    		&lt;nav class=&quot;navbar fixed-bottom navbar-expand-lg navbar-light bg-light&quot;&gt;
    			&lt;div class=&quot;container-fluid&quot;&gt;
    				&lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;Navbar&lt;/a&gt;
    				&lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarSupportedContent&quot; aria-controls=&quot;navbarSupportedContent&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;
    					&lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
    				&lt;/button&gt;
    				&lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarSupportedContent&quot;&gt;
    					&lt;ul class=&quot;navbar-nav&quot;&gt;
    						&lt;li class=&quot;nav-item&quot;&gt;
    							&lt;a class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;#&quot;&gt;StrindbergAppen&lt;/a&gt;
    						&lt;/li&gt;
    						&lt;li class=&quot;nav-item&quot;&gt;
    							&lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Bilder p&#229; August Strindberg&lt;/a&gt;
    						&lt;/li&gt;
    						
    						&lt;li class=&quot;nav-item&quot;&gt;
    							&lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Betygs&#228;tt Strindberg&lt;/a&gt;
    						&lt;/li&gt;
    						&lt;li class=&quot;nav-item&quot;&gt;
    							&lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Om Strindbergappen&lt;/a&gt;
    						&lt;/li&gt;
    					&lt;/ul&gt;
    				&lt;/div&gt;
    			&lt;/div&gt;
    		&lt;/nav&gt;
    		&lt;!-- End of Navbar! --&gt;
    		&lt;div&gt;
    			&lt;!-- page content --&gt;
    			&lt;h1&gt;August Strindberg&lt;/h1&gt;
    			&lt;picture&gt;
    				&lt;source media=&quot;(min-width: 800px)&quot; srcset=&quot;./img/hero/hero_medium.jpg&quot;&gt;
    				&lt;source media=&quot;(min-width: 1280px)&quot; srcset=&quot;./img/hero/hero_large.jpg&quot;&gt;
    				&lt;img src=&quot;./img/hero/hero_small.jpg&quot; alt=&quot;Gatubild fr&#229;n sekelskiftets Stockholm&quot; style=&quot;width:100%;&quot;&gt;
    			&lt;/picture&gt;
    			&lt;div class=&quot;container&quot;&gt;
    				&lt;h2&gt;Biografi&lt;/h2&gt;
    				&lt;picture class=&quot;left-align&quot;&gt;
    					&lt;source media=&quot;(min-width: 800px)&quot; srcset=&quot;./img/poet/poet_250x500.jpg, ./img/poet/poet_250x500@2.jpg 2x&quot;&gt;
    					&lt;source media=&quot;(min-width: 375px)&quot; srcset=&quot;./img/poet/poet_125x250.jpg, ./img/poet/poet_250x500.jpg 2x&quot;&gt;
    					&lt;img class=&quot;left-align&quot; src=&quot;./img/poet/poet_250x500.jpg&quot; alt=&quot;August Strindberg by Robert Roesler, circa 1881&quot;&gt;
    				&lt;/picture&gt;
    				&lt;p&gt;
    					Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime saepe praesentium error placeat ullam tempore
    					magni enim, debitis aliquam mollitia similique ipsa ipsum sunt ratione natus expedita cumque repellendus
    					provident?
    					Tempore itaque nostrum eligendi deleniti dolores ipsam repudiandae ipsum culpa exercitationem harum.
    					Distinctio aliquam ducimus illo modi nihil quis minus ullam rerum sapiente doloribus! Fugit, provident?
    					Voluptate nemo excepturi ducimus.
    					Corrupti accusantium perspiciatis ducimus vitae similique deserunt repellendus laudantium numquam velit
    					excepturi quidem, molestiae quos, eveniet ut. Unde consequatur ad repellat, natus maiores recusandae facilis
    					laboriosam doloremque maxime eveniet aliquid?
    					Aperiam voluptates quibusdam delectus quasi cum nobis nostrum ratione architecto fugiat exercitationem?
    					Animi aliquid, quaerat placeat voluptatem tempore mollitia assumenda eaque quae officiis amet tempora,
    					reprehenderit cumque? Quod, quasi accusantium.
    					Debitis tenetur atque temporibus ratione totam optio, illum officia provident eos repellat accusamus
    					excepturi maxime veniam neque nobis odio inventore sit laborum, dolorum perspiciatis. Eligendi non
    					architecto repellat inventore nam.
    				&lt;/p&gt;
    			&lt;/div&gt;
    		&lt;/div&gt;
    	&lt;/div&gt;
    
    	&lt;div id=&quot;page2&quot; class=&quot;page&quot;&gt;
    		&lt;!-- navbar --&gt;
    		&lt;nav class=&quot;navbar&quot;&gt;
    			&lt;button class=&quot;nav1 navbar-btn btn btn-primary active&quot; type=&quot;button&quot; onclick=&quot;showPage(1);&quot;&gt;Go to page 1&lt;/button&gt;
    			&lt;button class=&quot;nav2 navbar-btn btn btn-primary&quot; type=&quot;button&quot; onclick=&quot;showPage(2);&quot;&gt;Go to page2&lt;/button&gt;
    			&lt;button class=&quot;nav3 navbar-btn btn btn-primary&quot; type=&quot;button&quot; onclick=&quot;showPage(3);&quot;&gt;Go to page3&lt;/button&gt;
    		&lt;/nav&gt;
    		&lt;!-- page content --&gt;
    		&lt;h1&gt;Example page 2&lt;/h1&gt;
    		&lt;p&gt;
    			Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusantium maxime expedita culpa? Nostrum
    			perspiciatis perferendis dolore atque fuga inventore blanditiis! Minus mollitia dolorum nesciunt in magni
    			necessitatibus minima porro officia.
    			Corrupti fuga maiores aut eligendi id quasi necessitatibus. A nihil, repellendus quia dolores magnam
    			temporibus cum molestiae debitis. Eveniet, dolor voluptates? Officiis rerum aliquid repellendus quia dolore
    			omnis optio cum.
    			Beatae illum est et sint hic magnam, dignissimos quos excepturi nihil harum minus deserunt odio deleniti
    			praesentium eum adipisci fuga sequi porro, dolore cupiditate eligendi rerum distinctio reiciendis?
    			Blanditiis, incidunt.
    		&lt;/p&gt;
    	&lt;/div&gt;
    
    	&lt;div id=&quot;page3&quot; class=&quot;page&quot;&gt;
    		&lt;!-- navbar --&gt;
    		&lt;nav class=&quot;navbar&quot;&gt;
    			&lt;button class=&quot;nav1 navbar-btn btn btn-primary active&quot; type=&quot;button&quot; onclick=&quot;showPage(1);&quot;&gt;Go to page 1&lt;/button&gt;
    			&lt;button class=&quot;nav2 navbar-btn btn btn-primary&quot; type=&quot;button&quot; onclick=&quot;showPage(2);&quot;&gt;Go to page2&lt;/button&gt;
    			&lt;button class=&quot;nav3 navbar-btn btn btn-primary&quot; type=&quot;button&quot; onclick=&quot;showPage(3);&quot;&gt;Go to page3&lt;/button&gt;
    		&lt;/nav&gt;
    		&lt;!-- page content --&gt;
    		&lt;h1&gt;Example page 3&lt;/h1&gt;
    		&lt;p&gt;
    			Lorem ipsum dolor, sit amet consectetur adipisicing elit. Molestiae explicabo tempora ullam cumque, obcaecati
    			aut sed inventore excepturi, voluptatibus ratione laborum incidunt quod. Cum quis eos adipisci consequatur
    			ipsa. Sed!
    			Voluptatum voluptas sunt tenetur porro maiores veritatis, ipsam libero? Nesciunt ea quas iusto ducimus
    			suscipit eos quibusdam. Doloremque cum fugiat, tempora qui temporibus delectus. Fuga quaerat accusamus non
    			iusto delectus.
    			Esse a sit et nobis ducimus sint, porro, quod accusamus exercitationem voluptatum placeat sed. Soluta,
    			blanditiis aliquam consectetur rem aliquid itaque tempore ea corporis recusandae? Dignissimos sit expedita
    			commodi quibusdam.
    			Illo voluptates culpa assumenda recusandae explicabo ab pariatur? Temporibus qui dolorum expedita culpa
    			animi eligendi pariatur fuga dolorem ipsum, alias hic unde, nulla tenetur odio saepe enim aut ratione
    			laboriosam!
    		&lt;/p&gt;
    	&lt;/div&gt;
    	
    	&lt;script&gt;
    	  feather.replace()
    	&lt;/script&gt;
    &lt;/body&gt;
    
    &lt;/html&gt;

</details>


# 答案1
**得分**: 1

**编辑**:看起来你不需要将它放在正文中,但是你有相同的行两次是导致问题的原因。删除指定的行将解决你的问题。

我已经解决了你的问题。你没有正确实现Bootstrap 5。你有两个这样的行:`<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>`。都删除掉,但将这行保存到你的剪贴板。然后粘贴一个**在body内**。

根据getbootstrap.com上的文档,脚本应该放在**body**的末尾,而不是**head**中。

移动那行后它将起作用。

<details>
<summary>英文:</summary>

...............................
**Edit**: Looks like you don&#39;t need to have it in the body, but the fact that you have the same line twice is what is giving you the issue. Deleting the specified line will solve your issue.
...............................

I have solved your problem. You are not implementing Bootstrap 5 properly. You have two instances of this line: `&lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js&quot;&gt;&lt;/script&gt;`. Delete them both but save the line to your clipboard. Then paste one **inside of the body**.

According to the documentation at getbootstrap.com, the script should be at the end of the **body**, *not* in **head**.

It will work after you move that line.

</details>



huangapple
  • 本文由 发表于 2023年7月10日 20:19:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定