如何创建:全页标签页
学习如何使用 CSS 和 JavaScript 创建覆盖整个浏览器窗口的全页标签页(全屏标签页)。
全页标签页
单击链接可显示 "current" 页面:
Home
Home is where the heart is..
News
Some news this fine day!
Contact
Get in touch, or swing by for a cup of coffee.
About
Who we are and what we do.
创建单页标签页
第一步 - 添加 HTML:
<button class="tablink" onclick="openPage('Home', this, 'red')">Home</button> <button class="tablink" onclick="openPage('News', this, 'green')" id="defaultOpen">News</button> <button class="tablink" onclick="openPage('Contact', this, 'blue')">Contact</button> <button class="tablink" onclick="openPage('About', this, 'orange')">About</button> <div id="Home" class="tabcontent"> <h3>Home</h3> <p>Home is where the heart is..</p> </div> <div id="News" class="tabcontent"> <h3>News</h3> <p>Some news this fine day!</p> </div> <div id="Contact" class="tabcontent"> <h3>Contact</h3> <p>Get in touch, or swing by for a cup of coffee.</p> </div> <div id="About" class="tabcontent"> <h3>About</h3> <p>Who we are and what we do.</p> </div>
创建按钮以打开特定的标签页内容。所有带有 class="tabcontent"
的 <div>
元素默认都是隐藏的(通过 CSS 和 JS)。当用户点击按钮时,它会打开与这个按钮“匹配”的标签页内容。
第二步 - 添加 CSS:
设置链接和标签页内容(全页)的样式:
/* 设置 body 和 document 的高度为 100%,以启用“全页标签页” body, html { height: 100%; margin: 0; font-family: Arial; } /* 设置标签页链接的样式 */ .tablink { background-color: #555; color: white; float: left; border: none; outline: none; cursor: pointer; padding: 14px 16px; font-size: 17px; width: 25%; } .tablink:hover { background-color: #777; } /* 设置标签页内容的样式(并为整页内容添加高度:100%) */ .tabcontent { color: white; display: none; padding: 100px 20px; height: 100%; } #Home {background-color: red;} #News {background-color: green;} #Contact {background-color: blue;} #About {background-color: orange;}
第三步 - 添加 JavaScript:
function openPage(pageName, elmnt, color) { // 默认隐藏所有 class="tabcontent" 的元素 var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // 删除所有标签页链接/按钮的背景颜色 tablinks = document.getElementsByClassName("tablink"); for (i = 0; i < tablinks.length; i++) { tablinks[i].style.backgroundColor = ""; } // 显示具体标签页内容 document.getElementById(pageName).style.display = "block"; // 为用于打开标签页内容的按钮添加特定的颜色 elmnt.style.backgroundColor = color; } // 获取 id="defaultOpen" 的元素并点击它 document.getElementById("defaultOpen").click();
相关页面
教程:如何创建标签页