This article example shares the specific code of JS to implement Baidu search box for your reference. The specific content is as follows Implementation principleWhen dynamically inputting keywords into the input box, the current keyword is used as the value after the question mark parameter. Because Baidu's interface is used across domains, an Ajax request is created across domains through JSONP. The callback function handles the return value. I tried to study Baidu's interface and found that the native XHR interface parameters are a bit complicated (Baidu should have considered many situations). I found a 2345 navigation, randomly entered a letter s in the input box, opened Network, and found that it also sent a request to an address of Baidu. The '&wd=s' after the question mark sent this keyword, and '&cb=' should be the callback processing function, and its Type is also script. 2345 navigation should also obtain data from Baidu through JSONP. var script = document.createElement("script"); script.src = "https://www.baidu.com/su?&wd=" + encodeURI(this.value.trim()) + "&p=3&cb=handleSuggestion"; document.body.appendChild(script); I clicked on that request and saw the returned data. The result is returned in the form of an object. q corresponds to the search keyword, and s corresponds to the returned results (in array form) Later, you only need to dynamically create the li tag, set the content inside, and pay attention to other details. 1. Use flex layout to achieve horizontal and vertical centering of the search box. After setting the flex attribute, I found that it was not centered horizontally and vertically. At that time, I set the parent box height: 100%, and found that if I set the height to a specific value, it can be centered. I suspected that the % height setting was invalid. I checked and found that the height percentage is relative to the parent box, which is the body. By default, html and body have no height set. In addition, in the layout, for block boxes that do not have a set width and height, the width defaults to 100%, and the height is naturally expanded by the content inside. 2. Get the commonly used DOM nodes first to avoid frequent subsequent queries and operations on the DOM. 3. In order to avoid sending requests frequently during the input process (if you type fast), the request function is throttled and the interval is adjusted to 130ms, which is just right. If the time is longer, there will be a sense of lag. The arrow function in ES6 is used to avoid the problem of this pointing in setTimeout. 4. In the callback function:
5. Since li is created dynamically, when you click the li tag or click "Search" to jump to Baidu for search, the event bubbling principle is used to delegate events. Compatibility issues are not considered here: e = e || window.event; target = e.target || e.srcElement; 6. In addition to click events, keyboard events - the enter key and the up and down keys are all registered for event delegation. Finally, you can use the up and down keys on the keyboard and the mouse to select, and click "Search" or the Enter key to jump to the search. Code:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Compatibility View --> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta content="More convenient and faster search, thus achieving twice the result with half the effort" name="description"> <title>search you want</title> <style> html { height: 100%; } body { background: #f0f3ef; height: 100%; } .container { height: 100%; display: flex; justify-content: center; align-items: center; flex-direction: column; } .bgDiv { box-sizing: border-box; width: 595px; height: 55px; position: relative; /* position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); */ } .search-input-text { border: 1px solid #b6b6b6; width: 495px; background: #fff; height: 33px; line-height: 33px; font-size: 18px; padding: 3px 0 0 7px; } .search-input-button { width: 90px; height: 38px; color: #fff; font-size: 16px; letter-spacing: 3px; background: #3385ff; border: .5px solid #2d78f4; margin-left: -5px; vertical-align: top; opacity: .9; } .search-input-button:hover { opacity: 1; box-shadow: 0 1px 1px #333; cursor: pointer; } .suggest { width: 502px; position: absolute; top: 38px; border: 1px solid #999; background: #fff; display: none; } .suggest ul { list-style: none; margin: 0; padding: 0; } .suggest ul li { padding: 3px; font-size: 17px; line-height: 25px; cursor: pointer; } .suggest ul li:hover { background-color: #e5e5e5 } </style> </head> <body> <div class="container"> <div class="bgDiv"> <input type="text" class="search-input-text" value="" autofocus placeholder="Keyword"> <input type="button" value="Search" class="search-input-button" id="btn"> <div class="suggest"> <ul id="search-result"> </ul> </div> </div> </div> <script> var suggestContainer = document.getElementsByClassName("suggest")[0]; var searchInput = document.getElementsByClassName("search-input-text")[0]; var bgDiv = document.getElementsByClassName("bgDiv")[0]; var searchResult = document.getElementById("search-result"); // Clear the suggestion box content function clearContent() { var size = searchResult.childNodes.length; for (var i = size - 1; i >= 0; i--) { searchResult.removeChild(searchResult.childNodes[i]); } }; var timer = null; // Register the input box keyboard lift event searchInput.onkeyup = function (e) { suggestContainer.style.display = "block"; // If the input box content is empty, clear the content and no cross-domain request is required if (this.value.length === 0) { clearContent(); return; } if (this.timer) { clearTimeout(this.timer); } if (e.keyCode !== 40 && e.keyCode !== 38) { // Function throttling optimization this.timer = setTimeout(() => { // Create script tag JSONP cross-domain var script = document.createElement("script"); script.src = "https://www.baidu.com/su?&wd=" + encodeURI(this.value.trim()) + "&p=3&cb=handleSuggestion"; document.body.appendChild(script); }, 130) } }; // callback function handleSuggestion(res) { // Clear the previous data! ! clearContent(); var result = res.s; // Intercept the first five search suggestions if (result.length > 4) { result = result.slice(0, 5) } for (let i = 0; i < result.length; i++) { // Dynamically create li tag var liObj = document.createElement("li"); liObj.innerHTML = result[i]; searchResult.appendChild(liObj); } // Self-executing anonymous function--delete the script tag used for cross-domain (function () { var s = document.querySelectorAll('script'); for (var i = 1, len = s.length; i < len; i++) { document.body.removeChild(s[i]); } })() } function jumpPage() { window.open(`https://www.baidu.com/s?word=${encodeURI(searchInput.value)}`); } // Event delegate clicks the li tag or clicks the search button to jump to the Baidu search page bgDiv.addEventListener("click", function (e) { if (e.target.nodeName.toLowerCase() === 'li') { var keywords = e.target.innerText; searchInput.value = keywords; jumpPage(); } else if (e.target.id === 'btn') { jumpPage(); } }, false); var i = 0; var flag = 1; // Event delegation to listen for keyboard events bgDiv.addEventListener("keydown", function (e) { var size = searchResult.childNodes.length; if (e.keyCode === 13) { jumpPage(); }; //Keyboard down eventif (e.keyCode === 40) { if (flag === 0) { i = i + 2; } flag = 1; e.preventDefault(); if (i >= size) { i = 0; } if (i < size) { searchInput.value = searchResult.childNodes[i++].innerText; } }; //Keyboard up eventif (e.keyCode === 38) { if (flag === 1) { i = i - 2; } flag = 0; e.preventDefault(); if (i < 0) { i = size - 1; } if (i > -1) { searchInput.value = searchResult.childNodes[i--].innerText; } }; }, false); // Click anywhere else on the page to make the search results box disappear document.onclick = () => clearContent() </script> </body> </html> The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM. You may also be interested in:
|
<<: How to install and configure the Apache Web server
>>: How to get datetime data in mysql, followed by .0
The company's business scenario requires the ...
Detailed explanation of creating MySql scheduled ...
In actual work, JavaScript regular expressions ar...
Preface Sometimes when we view database data, we ...
1. Environment: MySQL-5.0.41-win32 Windows XP Pro...
MySQL bidirectional backup is also called master-...
Copy code The code is as follows: <!DOCTYPE HT...
dl:Definition list Definition List dt:Definition t...
Now that we have finished the transform course, l...
1. Components and implemented functions Keepalive...
Preface A character set is a set of symbols and e...
Two ways to navigate the page Declarative navigat...
This axios package is used in the vue3 demo. For ...
This article example shares the specific code of ...
Table of contents Install Configuration Common Mi...