Function description and end result
Enter text in the search box and automatically match the corresponding data.
It works like this:
The original data included cities in the United States in this format
[{"city": "New York", "growth_FROM_2000_TO_2013 ": "4.8%", "latitude": 40.7127837, "longitude": - 74.0059413, "population" : "8405837", "rank" : "1", "state" : "New York"}, {...}]Copy the code
Holding the principle of localization, I found the data of a Chinese province, city and county on the Internet, and the data format is like this
[{"provinceCode": "110000", "provinceName": "provinceType": 1, "cities": [{"cityCode": "110100", "cityName": Counties :[{"countyCode": "110101", "countyName": "isCity": 1, "isCapital": true, "counties":[{"countyCode": "110101", "countyName": "eastside ", "isCity": false }, { ... } ] ] ]Copy the code
This data will be used for the next city search
style
Fold the paper using Translate and shadows
First of all, this is a normal Li
< li class = "result - the item" > < p class = "item - code" > region code < / p > < p class = "item - the name" > city name < / p > < / li >Copy the code
Add the shadow
background: linear-gradient(to top, #ffffff 0%, #efefef 100%);
Copy the code
Add special effects
transform: perspective(100px) rotateX(-3deg) translateY(3px);
Copy the code
It’s pretty good
function
Get user input
Because the matched data is in Chinese, the value entered by the user is obtained only when the text is confirmed. So instead of listening for input events, listen for comPositionEnd events.
input_dom.addEventListener("compositionend", (event) => {
console.log(event.data);
});
Copy the code
If you want to type and press Enter to search, you can listen for the change event
Find matching data
Let’s look at city.json:
- Provincial-level municipalities, autonomous regions, and provinces are provincial-level. ProvinceName = provinceType
- Only municipalities and provinces need to match the cityName under Cities
So I wrote this method (…)
function getCityList(cname) { const list = []; city.forEach((item) => { if (item.provinceName.includes(cname)) { list.push({ name: item.provinceName, code: item.provinceCode }); } if (item.provinceType ! == 1) { item.cities.forEach((i) => { if (i.cityName.includes(cname)) { list.push({ name: i.cityName, code: i.cityCode }); }}); }}); return list; }Copy the code
It is worth mentioning that “aaa”.includes(“) will return true, which means you enter the city name once to find it, and then delete all the names to display the data for all the cities.
Output matching data to HTML
function addliDom(mlist) {
let str = "";
mlist.forEach((item) => {
str += `<li class="result-item"><p class="item-code">${item.code}</p><p class="item-name">${item.name}</p></li>`;
});
ul_dom.innerHTML = html_str + str;
}
Copy the code