如何創建:全屏搜索

學習如何使用 CSS 和 JavaScript 創建全屏搜索框。

親自試一試

如何創建全屏搜索框

第一步 - 添加 HTML:

<div id="myOverlay" class="overlay">
  <span class="closebtn" onclick="closeSearch()" title="Close Overlay">x</span>
  <div class="overlay-content">
    <form action="action_page.php">
      <input type="text" placeholder="Search.." name="search">
      <button type="submit"><i class="fa fa-search"></i></button>
    </form>
  </div>
</div>

第二步 - 添加 CSS:

/* 黑色背景疊加效果 */
.overlay {
  height: 100%;
  width: 100%;
  display: none;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0, 0.9); /* 黑色,有一點透視(或透明)的效果 */
}
/* 內容 */
.overlay-content {
  position: relative;
  top: 46%;
  width: 80%;
  text-align: center;
  margin-top: 30px;
  margin: auto;
}
/* 關閉按鈕 */
.overlay .closebtn {
  position: absolute;
  top: 20px;
  right: 45px;
  font-size: 60px;
  cursor: pointer;
  color: white;
}
.overlay .closebtn:hover {
  color: #ccc;
}
/* 設置搜索框的樣式 */
.overlay input[type=text] {
  padding: 15px;
  font-size: 17px;
  border: none;
  float: left;
  width: 80%;
  background: white;
}
.overlay input[type=text]:hover {
  background: #f1f1f1;
}
/* 設置提交按鈕的樣式 */
.overlay button {
  float: left;
  width: 20%;
  padding: 15px;
  background: #ddd;
  font-size: 17px;
  border: none;
  cursor: pointer;
}
.overlay button:hover {
  background: #bbb;
}

第三步 - 添加 JavaScript:

使用 JavaScript 打開和關閉疊加/全屏效果:

// 打開全屏搜索框
function openSearch() {
  document.getElementById("myOverlay").style.display = "block";
}
// 關閉全屏搜索框
function closeSearch() {
  document.getElementById("myOverlay").style.display = "none";
}

親自試一試