如何創建:全頁標簽頁

學習如何使用 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();

親自試一試

相關頁面

教程:如何創建標簽頁