如何 - 全页选项卡
了解如何使用 CSS 和 JavaScript 创建覆盖整个浏览器窗口的全页选项卡。
全页选项卡
点击链接以显示“当前”页面
主页
家是心灵的归宿..
新闻
今天有些新闻!
联系
保持联系,或者来一杯咖啡。
关于
我们是谁,我们做什么。
创建单页选项卡
步骤 1) 添加 HTML
示例
<button class="tablink" onclick="openPage('Home', this, 'red')">主页</button>
<button class="tablink" onclick="openPage('News', this, 'green')" id="defaultOpen">新闻</button>
<button class="tablink" onclick="openPage('Contact', this, 'blue')">联系方式</button>
<button class="tablink" onclick="openPage('About', this, 'orange')">关于</button>
<div id="Home" class="tabcontent">
<h3>主页</h3>
<p>家是心灵的归宿..</p>
</div>
<div id="News" class="tabcontent">
<h3>新闻</h3>
<p>今天有些新闻!</p>
</div>
<div id="Contact" class="tabcontent">
<h3>联系方式</h3>
<p>Get in touch, or swing by for a cup of coffee.</p>
</div>
<div id="About" class="tabcontent">
<h3>关于</h3>
<p>Who we are and what we do.</p>
</div>
创建按钮以打开特定的标签内容。所有具有 class="tabcontent"
的 <div> 元素默认都隐藏(通过 CSS & JS)。当用户点击一个按钮时 - 它将打开与该按钮“匹配”的标签内容。
步骤 2) 添加 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;
}
/* 样式化选项卡内容(并为全页内容添加 height: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;}
步骤 3) 添加 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();
自己动手试一试 »
提示:同时查看 如何 - 标签页。