如何使用 CSS 手動設定 Google 自定義搜尋的樣式?
你有沒有嘗試過構建自定義搜尋引擎?如果有,你就會知道這需要花費多少精力。首先,我們需要建立一個搜尋演算法,以便在任何使用者搜尋時顯示最佳匹配結果。這可能需要花費大量時間。
與其浪費時間建立自己的搜尋引擎,我們為什麼不使用 Google 自定義搜尋引擎呢?沒錯!Google 允許我們在我們的網站上整合搜尋引擎,並且當任何使用者在我們網站上搜索某些內容時,Google 會處理所有事情。
將 Google 自定義搜尋引擎整合到網站中
使用者應按照以下步驟將 Google 自定義搜尋引擎整合到任何網站中,從建立帳戶到建立搜尋功能。
步驟 1 − 在 自定義搜尋引擎 上建立一個帳戶。成功建立帳戶後,您將看到以下介面。您可以點選“建立您的第一個搜尋引擎!”文字。
步驟 2 − 現在,填寫所需詳細資訊並在您想要使用 Google 自定義搜尋引擎的網站上新增網站連結。如果您想在任何網站上使用它,可以選擇“搜尋整個網路”單選元件。接下來,點選建立按鈕。
步驟 3 − 成功建立搜尋引擎後,使用者可以看到以下介面。複製以下程式碼並將其貼上到 html 檔案中。
我們已完全準備好將 Google 自定義搜尋引擎整合到我們的網站中。
語法
使用者可以按照以下語法使用 Google 自定義搜尋引擎。
<script async src="https://#/cse.js?cx=5085dc69f916047fa"> </script> <div class="gcse-search"></div>
使用者應將“<div class="gcse-search"></div>”程式碼放在他們想要新增 Google 自定義搜尋的任何位置。
示例
我們在下面的示例中將 Google 自定義搜尋引擎與 HTML 程式碼整合在一起。在 JavaScript 中,我們更改搜尋引擎的佔位符文字。我們使用 querySelector() 方法選擇 searchButton 和 serachBox,並替換其標題和佔位符文字。
我們添加了一些 CSS 以使搜尋更具樣式。每當使用者開始搜尋時,它會自動隱藏佔位符文字。
使用者可以在搜尋框中搜索任何內容,這將提供相關結果。
<html> <head> <style> body { padding: 1rem;} .gsc-control { font-family: arial, sans-serif; background-color: lightblue !important; width: 500px; border-radius: 3rem; padding: 7px 20px !important;} .gsc-input-box { border: 1px solid #dfe1e5;background: #fff; border-radius: 2rem; padding: 1px 10px;} #gsc-i-id1 { color: #000 !important; line-height: 1.2 !important; background: none !important; font-size: 1rem !important; } .gsc-search-button-v2 { padding: 0.5rem !important; cursor: pointer; border-radius: 50%; } </style> </head> <body> <h3> Creating the custom Google search using the GCSE </h3> <p> Search anything here </p> <!-- script from GCSE --> <script async src="https://#/cse.js?cx=5085dc69f916047fa"> </script> <div class="gcse-search"></div> <script> window.onload = function () { var placeHolderText = "Search on Tutorialspoint"; var searchBox = document.querySelector("#gsc-i-id1"); var searchButton = document.querySelector (".gsc-search-button-v2 svg title"); searchBox.placeholder = placeHolderText; searchBox.title = placeHolderText; searchButton.innerHTHL = placeHolderText; } </script> </body> </html>
使用者學習瞭如何將 Google 自定義搜尋整合到網站中。我們已將其與原生 JavaScript 整合,但使用者也可以將其與 ReactJS 和其他框架整合。
此外,此搜尋僅適用於 TutorialPoint 的網站,因為我們僅為此網站建立了它。如果使用者想在其網站上使用,則應在 Google 的自定義搜尋網站上建立一個帳戶,如教程開頭部分所示,並需要更改 Script 標籤。