html
<!-- 搜索框 -->
<div class="input"><input type="text" v-model="search_content" @input="replace_text(search_content)"@focus="search_show = true, replace_text(search_content)" @blur="search_show = false":placeholder="search_placeholder"><div class="icon"@click="navigateTo({ path: '/home/searchDetails/' + (search_content ? search_content : search_placeholder) })"><i class="iconfont icon-search" style="color:#fff;font-size:20px"></i></div><!-- 搜索列表 --><div class="search_ul" v-if="search_show"><div class="li" v-for="item, i in search_list" :key="i"><p v-html="item"></p></div></div>
</div>
js
/**搜索内容*/
const search_content = ref("")
/**搜索框默认值 根据最近搜索推荐*/
const search_placeholder = ref("vue")
/**是否显示搜索列表*/
const search_show = ref(false)
/**搜索推荐渲染列表*/
const search_list: any = ref([])
/**历史搜索*/
const search_history: any = ref([])
/**模拟后端返回的数据*/
const search_data = ref(["搜索内容","搜索内容vue","搜索内容vue2","搜索内容vue3","搜索内容vue2和vue3","搜索内容vue3和Nuxt3",
])
/*** 修改搜索内容的文字颜色* @text 搜索内容*/
function replace_text(text: string) {console.log("搜索内容:", text);/**判断搜索内容不为空展示推荐搜索*/if (text.trim() != "") {search_list.value = []search_data.value.forEach((item: any) => {/**替换搜索内容为标签添加样式*/search_list.value.push(`${item.replaceAll(text, "<span style='color:#c4302c;font-size:16px'>" + text + "</span>")}`)})} else {/**判断搜索历史是否为空*/if (search_history.value.length != 0) {/**不为空显示历史搜索*/search_list.value = search_history.value} else {/**为空显示推荐搜索*/search_list.value = ["推荐搜索内容","前端页面怎么写","怎么让搜索的字变成红色","字变成红色的css怎么写",]}}
}
scss样式
/**搜索框*/
/**定义主题颜色*/
$color: #c4302c;
.input {width: 234px;height: 32px;border: 2px solid $color;border-radius: 120px;position: relative;/**搜索列表*/.search_ul {position: absolute;left: 50%;bottom: -200px;transform: translateX(-50%);background-color: #fff;box-shadow: 0px 2px 20px 0px #EBEBwidth: 235px;height: 190px;overflow: hidden;border-radius: 10px;text-align: left;padding: 10px 0;.li {width: 100%;font-size: 16px;color: #909399;cursor: pointer;height: 30px;background-color: #fff;p {padding: 5px 10px;font-size: 16px;&:hover {background-color: #f0f}}}}input {position: absolute;top: 50%;left: 10px;transform: translateY(-50%);width: 70%;height: 90%;border: none;outline: none;}.icon {cursor: pointer;position: absolute;top: 50%;right: 0;transform: translate(1px, -50%);width: 44px;height: 30px;border-radius: 15px;background: $color;display: flex;justify-content: center;align-items: center;}
效果
搜索内容是写死的,搜索列表数据由后端返回,前端进行循环处理