首页 > 解决方案 > 如果我以星号或所选字母开始书写,如何在搜索字段中定义文本颜色?

问题描述

使用此 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>

标签: javascripthtml

解决方案


您可以尝试使用.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>


推荐阅读