Đăng nhập
Bạn chưa có tài khoản? Đăng ký.
Bạn đã quên password?
Trong bài thực hành này. chúng ta sẽ tìm hiểu cách tạo một Search form trên thanh menu bar bằng HTML, CSS và JavaScript.
Bước 1) Thêm HTML:
Ví dụ
<div class="containerx"> <div class="menubar"> <a class="links" href="#">Home</a> <a class="links" href="#">Contact</a> <a class="links" href="#">About</a> </div> <div class="searchform"> <form action="/action_page.php" method="post"> <input id="text" type="text" name="search" placeholder="Search" required="required" /> <input id="button" role="button" type="submit" value="Submit" /> </form> </div> </div>
Bước 2) Thêm CSS:
Ví dụ
/* Tạo kiểu cho vùng chứa */ .containerx { background-color:#ddd; overflow:hidden; position:relative; border-radius:5px; } /* Menu bar căn trái */ .containerx > .menubar { float:left; } /* Search form căn phải */ .containerx > .searchform { float:right; } /* Tạo kiểu cho phần tử a */ .menubar > a { text-decoration:none; display:inline-block; padding:20px; color:black; float:left; text-align:center; } /* Thêm hiệu ứng khi hover */ .menubar > a:hover:not(.active) { background-color:royalblue; color:white; } /* Bố cục vọ trí cho vùng chứa search form */ .searchform { position:absolute; top:50%; right:20px; transform:translateY(-50%); } /* Tạo kiểu chung cho phần tử input */ form > input { border:none; outline:none; padding:10px; float:left; } form > input[type="text"] { border-radius:5px 0px 0px 5px; } form > input[type="text"]:focus { box-shadow:-2px 0 orange, 0 -2px orange, 0 2px orange; } form > input[type="submit"] { background-color:royalblue; color:white; border-radius:0px 5px 5px 0; cursor:pointer; } form > input[type="submit"]:hover { background-color:green; } /* Tạo lớp active */ .menubar > .active { background-color:red; color:white; } /* Thay đổi cách hiển thị khi màn hình nhỏ hơn 700px */ @media screen and (max-width:700px) { .containerx > .menubar, .containerx > .searchform { float:none; } .containerx { padding-bottom:10px; } .containerx > .searchform { position:static; transform:translateX(20%); padding-top:10px; } .menubar > a { display:block; float:none; width:100%; } }
Bước 3) Thêm JavaScript:
Ví dụ
<script> // Khai báo các biến và lấy giá trị var links, i, j, text, button; links = document.getElementsByClassName('links'); text = document.getElementById('text'); button = document.getElementById('button'); // Gán lớp active for(i = 0; i < links.length; i++) { links[i].onclick = function() { for(j = 0; j < links.length; j++) { links[j].classList.remove("active"); } this.classList.add("active"); } } links[0].click(); // Thêm hiệu ứng bóng khi được lấy nét text.onfocus = function() { button.style.boxShadow = "0 -2px orange, 2px 0 orange, 0 2px orange"; } // Xóa hiệu ứng bóng khi thôi lấy nét text.onblur = function() { button.style.boxShadow = "none"; } </script>