如何使用 CSS 和 JavaScript 创建全屏搜索框?

cssjavascriptweb developmentfront end technology

以下是使用 CSS 和 JavaScript 创建全屏搜索框的代码 −

示例

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/fontawesome.min.css">
<style>
body {
   font-family: Arial;
}
* {
   box-sizing: border-box;
}
.showBtn {
   background: #008b0c;
   border: none;
   color:white;
   padding: 10px 15px;
   font-size: 20px;
   cursor: pointer;
   opacity: 0.8;
}
.showBtn:hover {
   opacity: 1;
}
.overlaySearch {
   height: 100%;
   width: 100%;
   display: none;
   position: fixed;
   z-index: 1;
   top: 0;
   left: 0;
   background-color: rgba(132, 150, 155, 0.747);
}
.searchBar {
   position: relative;
   top: 46%;
   width: 80%;
   text-align: center;
   margin-top: 30px;
   margin: auto;
}
.overlaySearch .hideBtn {
   position: absolute;
   top: 20px;
   right: 45px;
   font-size: 60px;
   cursor: pointer;
   color: rgb(255, 0, 0);
   opacity: 0.8;
}
.overlaySearch .hideBtn:hover {
   opacity: 1;
}
.overlaySearch input[type=text] {
   padding: 15px;
   font-size: 17px;
   border: none;
   float: left;
   width: 80%;
   background: white;
}
.overlaySearch input[type=text]:hover {
   background: #f1f1f1;
}
.overlaySearch button {
   float: left;
   width: 20%;
   padding: 15px;
   background: rgb(54, 21, 241);
   font-size: 17px;
   border: none;
   color:white;
   cursor: pointer;
   opacity: 0.8;
}
.overlaySearch button:hover {
   opacity: 1;
}
</style>
</head>
<body>
<div class="overlaySearch" >
<span class="hideBtn">×</span>
<div class="searchBar">
<form >
<input type="text" placeholder="Search Here.." ">
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
<h1>Fullscreen Search Example</h2>
<button class="showBtn">Open Search Box</button>
<h2>Click on the above button to open search box in full screen</h2>
<script>
document.querySelector('.hideBtn').addEventListener('click',hideSearch);
document.querySelector('.showBtn').addEventListener('click',showSearch);
function showSearch() {
   document.querySelector('.overlaySearch').style.display = "block";
}
function hideSearch() {
   document.querySelector('.overlaySearch').style.display = "none";
}
</script>
</body>
</html>

输出

上述代码将产生以下输出 −

点击打开搜索框按钮 −


相关文章