大家好,我卡颂。

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大,然而毕竟播种了高兴......

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