实现了实时搜索显示并将匹配的字添加颜色
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<link rel="icon" href="<%= BASE_URL + VUE_APP_ASSETS + '/' %>favicon2.ico" />
<title>搜索</title>
<style>
.nores {
font-size: 14px;
line-height: 18px;
color: #95A4B3;
position:absolute;
top:165px;
left:50%;
transform:translateX(-50%)
}
.search {
width:343px;
height:45px;
margin:20px auto;
background: #FFFFFF;
border: 1px solid #F0F0F0;
box-sizing: border-box;
border-radius: 8px;
display:flex;
align-items:center;
position:relative;
}
.delete {
display:none;
position:absolute;
top:13.5px;
right:12px;
width:18px;
height:18px;
background:url('http://fs.yqfw.cdyoue.com/FnW-tTBw809h_SV1IWAUmVhXzYnv') no-repeat center;
}
img{
width:20px;
height:20px;
margin:0 8px 0 12px
}
input{
width:100%;
border:none;
outline:none;
font-size: 14px;
line-height: 21px;
color: #333333;
position:relative;
box-sizing:border-box;
padding-right:30px
}
input::placeholder{
font-family: PingFang SC;
font-style: normal;
font-weight: normal;
font-size: 14px;
line-height: 21px;
color: #CCCCCC;
}
.list .items {
width:351px;
height:42px;
line-height:42px;
margin:0 auto;
color:#333333;
box-sizing:border-box;
border-bottom:1px solid #F4F4F8;
font-size:14px
}
.list .items:first-child{
margin-top:20px
}
.list .items:last-child{
border-bottom:none;
}
</style>
</head>
<body>
<div class="search">
<img src="http://fs.yqfw.cdyoue.com/Fq4-RXDEd2Iu1_HdjcNt0kKYOf_s" />
<input placeholder="搜索"/>
<div class="delete"></div>
</div>
<div class="list"></div>
<div class="nores">暂无数据</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
const data = {
'第一':['得到的','啊啊啊','事实上'],
'第二':['钱钱钱','呜呜呜','呃呃呃']
}
let arr = []
for(let i in data){
arr.push(...data[i])
}
$("input").bind("input propertychange",function(event){
var val = $("input").val()
$('.list').empty()
if(val != ''){
$('.delete').show()
for(let i of arr){
if(i.indexOf(val) != -1){
let result = replaceHandle(i,val)
$('.list').append('<div class="items">'+result+'</div>')
if($('.items').length != 0){
$('.nores').hide()
}else {
$('.nores').show()
}
}else {
}
}
}else{
$('.delete').hide()
$('.nores').show()
}
});
$('.delete').on('click',function(){
$("input").val('')
$('.delete').hide()
$('.list').empty()
$('.nores').show()
})
function replaceHandle(parentStr,searchText){
var res = new RegExp("("+searchText+")",'g');
parentStr = parentStr.replace(res,"<span style='color:#44A8F8;'>" + searchText+"</span>");
return parentStr;
}
</script>
</body>
</html>