关于前端:如何用CSS实现一个搜索引擎

2次阅读

共计 1868 个字符,预计需要花费 5 分钟才能阅读完成。

大家好,我卡颂。

CSS 中,咱们通过selector(选择器)抉择款式片段:

.title {color: red;}

简而言之,选择器 title 对应款式color: red;

换个角度,咱们也能够说:关键词 .title 对应数据color: red;

在咱们生存中,还有什么货色依赖这种对应关系呢?

一个很显然的例子:搜索引擎。

在搜索引擎中输出 关键词 ,搜索引擎通过检索,返回 关键词 对应的 数据.

既然情理都一样,那能不能用纯 CSS 实现一个搜索引擎呢?

别说,机(无)智(聊)的人还是很多的,真的有人搞了 CSS 实现的搜索引擎。

在该搜索引擎中输出员工姓名,会显示员工信息。

本文来聊聊他是如何实现的。

外围原理

最根本的,咱们须要一个搜寻框,和一个显示搜寻后果的容器。

<input type="search" value=""oninput="this.setAttribute('value', this.value)"
/>
<div id="result"></div>

留神 oninput 应用了一行 JS 代码,这也是引擎中惟一一行 JS 代码

咱们心愿输出 Tim#result 容器内显示搜寻后果Tim Carry

能够通过 属性选择器 + 伪元素 实现:

input[value="tim" i] ~ #result:before {content: "Tim Carry";}

其中 属性选择器 中的 i 代表疏忽内容大小写。

这就是本搜索引擎的外围原理,实践上只有选择器规定越多,搜寻后果就越丰盛。

多个搜寻后果

让咱们持续扩大。假如有 150 个员工,为他们一一建设对应关系:

每个员工一个div

<div id="results">
  <div id="result0"></div>
  <div id="result1"></div>
  <div id="result2"></div>
  […]
  <div id="result148"></div>
  <div id="result149"></div>
  <div id="result150"></div>
</div>

每个员工一条搜寻后果:

#result0:before {content: "Aurora Pleguezelo"}
// […]
#result15:before {content: "Alexandre Collin"}
#result16:before {content: "Alexandre Meunier"}
#result17:before {content: "Alexandre Stanislawski"}
// […]
#result150:before {content: "Zo Asmail"}

接下来,设定搜寻规定,首先暗藏所有搜寻后果:

#results div {display: none}

而后,抉择一个粒度,建设搜寻规定,比方咱们抉择“姓”作为粒度:

input[value="alexandre" i] ~ #results #result15,
input[value="alexandre" i] ~ #results #result16,
input[value="alexandre" i] ~ #results #result17 {display: block}

当输出 alexandre 这个姓时,对应的后果会display: block

#result15:before {content: "Alexandre Collin"}
#result16:before {content: "Alexandre Meunier"}
#result17:before {content: "Alexandre Stanislawski"}

更近一步,姓名能够拆的更细,所以搜寻的粒度能够更细:

能够别离以 一个字母 两个字母 三个字母… 建设对应关系。

搜索词高亮

为了晋升体验,咱们还心愿 搜索词高亮

比方,输出 cle 后,搜寻后果姓名中 cle 是加粗显示的:

分为 2 步实现:

  1. 自定义字体

UTF-8 的公有区域,为每个字母定义对应的加粗字体,比方:m在该字体中对应\e64d

  1. 在搜寻后果中用加粗字体替换惯例字母

比方,输出 mar 的搜寻后果应该为:Marion Aguirre

将后果中的 Mar 替换为 \e64d \e661 \e672,也就是自定义字体中对应Mar 的粗体字母。

总结

依照这个设定,制约本搜索引擎的,只有作者的想象力了。

比方应用 flex 布局的 order 属性,竞价排名不是梦:

如果你思考一阵,略带纳闷的问:那 CSS 文件会不会很大?

哎,只能说,小了,格局小了。

尽管收录 150 个员工的 CSS 文件有 8MB 大,然而毕竟播种了高兴 ……

欢送退出人类高质量前端框架钻研群,带飞

正文完
 0