javascript - 如果我以星号或所选字母开始书写,如何在搜索字段中定义文本颜色?
问题描述
使用此 js 代码,我们可以在以星号开头时隐藏 div 或在以字母或其他符号开头时显示 div。我需要的是更改以星号开头的文本的颜色。也就是说,如果我以字母或符号开头,则 div 出现在下方并保持黑色,但如果我以星号开头,则 div 不会出现,但星号和我写的以下单词必须以绿色显示。
https://jsfiddle.net/z6cgxjek/
$('#search').keyup(function(event) {
$('#hello').show();
if(!event.target.value.trim() || event.originalEvent.charCode === 42 || event.target.value.startsWith("*")) {
$('#hello').hide();
} else {
$('#hello').show();
}
});
#hello {
display:none;
}
<input id="search" autocomplete="off"/>
<div id="hello" >Hello World!</div>
解决方案
您可以尝试使用.css()
来获取/设置一个或多个 CSS 属性。我也更喜欢输入事件而不是keyup:
$('#search').on('input', function(event) {
$('#hello').show();
if(!event.target.value.trim() || event.originalEvent.charCode === 42 || event.target.value.startsWith("*")) {
$('#hello').hide();
$(this).css({color: 'green'});
} else {
$('#hello').show();
$(this).css({color: ''});
}
});
#hello {
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search" autocomplete="off"/>
<div id="hello" >Hello World!</div>
推荐阅读
- winapi - HGDIOBJ objectHandle[1]中的objectHandle怎么可以是变长数组?
- android - 如何调整相对布局 videoView 的屏幕尺寸
- sql - SQL DELETE FROM 几个表
- go - 如何在 Struct 中声明类似空 Object/Struct 的东西?
- javascript - 地球观测图块优化
- flutter - 如何使用预先填充的本地数据库设置 dart objectbox?
- reactjs - Ant Design Table Extension CSV 导出问题
- android - 如何对我的存储库和视图模型进行单元测试?
- python - 数据集 TensorFlow Lite Model Maker 对象检测
- python - 如何在python中清除颜色matplotlib?