
如何使用HTML、CSS和jQuery實現網頁內搜尋功能
引言:
隨著網路的快速發展,搜尋引擎已經成為人們獲取資訊的重要途徑。然而,在某些情況下,我們可能需要在特定的網頁內實現搜尋功能,以便使用者能夠快速地找到自己想要的內容。本文將介紹如何使用HTML、CSS和jQuery實作網頁內搜尋功能,並給出具體的程式碼範例。
一、HTML部分程式碼:
首先,我們需要使用HTML來建立基本的網頁結構,並且加入一個搜尋框和一個用來展示搜尋結果的區域。程式碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <!DOCTYPE html>
<html lang= "en" >
<head>
<meta charset= "UTF-8" >
<meta http-equiv= "X-UA-Compatible" content= "IE=edge" >
<meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
<title>网页内搜索功能</title>
<style>
</style>
</head>
<body>
<div class = "search-container" >
<input type= "text" id= "search-input" placeholder= "请输入关键字..." >
<button id= "search-button" >搜索</button>
</div>
<div id= "search-results" >
<!-- 搜索结果显示在这里 -->
</div>
<script src= "https://code.jquery.com/jquery-3.6.0.min.js" ></script>
<script>
</script>
</body>
</html>
|
登入後複製
二、CSS部分程式碼:
接下來,我們需要使用CSS來美化搜尋框和搜尋結果區域的樣式。程式碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | .search-container {
text-align: center;
margin-top: 20px;
}
#search-input {
width: 300px;
height: 40px;
font-size: 16px;
padding: 5px 10px;
border: none;
border-radius: 4px;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
outline: none;
}
#search-button {
width: 80px;
height: 40px;
font-size: 16px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
margin-left: 10px;
cursor: pointer;
}
#search-results {
margin-top: 20px;
}
|
登入後複製
三、jQuery部分程式碼:
最後,我們使用jQuery來實作搜尋功能。程式碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $(document).ready( function () {
$( "#search-button" ).click( function () {
var keyword = $( "#search-input" ).val();
$( "p, h1, h2, h3, h4, h5, h6" ).each( function () {
var text = $(this).text();
if (text.includes(keyword)) {
$(this).css( "background-color" , "yellow" );
} else {
$(this).css( "background-color" , "" );
}
});
});
});
|
登入後複製
程式碼解釋:
- 首先,我們在$(document).ready()函數中編寫程式碼,並確保頁面載入完成後再執行。
- 當點擊搜尋按鈕時,我們取得搜尋框中的關鍵字,然後使用each()函數遍歷所有要搜尋的元素(這裡假設要搜尋的元素是頁面中的標題和段落)。
- 對於每個元素,我們透過text()函數取得其文字內容,並使用includes()函數判斷是否包含關鍵字。
- 如果包含關鍵字,我們透過css()函數設定背景顏色為黃色,表示符合到了結果;如果不包含關鍵字,我們清除先前符合的元素的背景顏色。
總結:
透過HTML、CSS和jQuery的結合,我們可以輕鬆實現網頁內搜尋功能。使用者可以在搜尋框中輸入關鍵字,點選搜尋按鈕後,頁面會將符合到關鍵字的元素高亮顯示出來,幫助使用者快速定位到自己想要的內容。以上就是有具體程式碼範例的使用說明,希望對大家有幫助。
以上是如何使用HTML、CSS和jQuery實現網頁內搜尋功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!