如何使用jQuery更改含有Font-Awesome内容的占位符?

bLu*_*dDy 6 javascript css jquery font-awesome

我想改变尝试attr()使用它的占位符属性:

$(this).attr("placeholder", " Mandatory field");
Run Code Online (Sandbox Code Playgroud)

但结果不是Font-Awesome图标,它看起来像这样:

" Mandatory field"
Run Code Online (Sandbox Code Playgroud)

不过,如果我放

<input type="text" class="mandatory_field form-control" id="affiliation" placeholder="&#xf0a4; Mandatory field"/>
Run Code Online (Sandbox Code Playgroud)

用CSS

.mandatory_field {  
   font-family: FontAwesome,"Helvetica Neue",Helvetica,Arial,sans-serif; 
}
Run Code Online (Sandbox Code Playgroud)

它有效,但我需要知道如何使用jQuery动态获取这些结果.

提前致谢.

zer*_*0ne 6

此解决方案仅需要:

  • 一行jQuery
  • CSS属性 font-family:FontAwesome
  • 根本没有HTML

您需要具有前缀的图标的特定CSS代码\u.Font-Awesome文档只有class和unicode.幸运的是,这个网站有你需要的东西.这是jQuery应该是什么:

$('.mandatory_field').attr('placeholder', '\uf0a4 Mandatory field');
Run Code Online (Sandbox Code Playgroud)

CSS和JavaScript字体实体之间的唯一区别在于JavaScript u的第二个字符位置.

在演示中,我还添加了一些带有::placeholder伪元素的样式作为奖励.您可以在不影响用户输入样式的情况下设置占位符样式.

演示

$('.mandatory_field').attr('placeholder', '\uf0a4 Mandatory field');
Run Code Online (Sandbox Code Playgroud)
/* With the exception of font-family:FontAwesome everything
|| is optional.
*/

input {
  font: inherit
}

.mandatory_field::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  color: red;
  font-family: FontAwesome;
  font-variant: small-caps;
}

.mandatory_field::-moz-placeholder {
  /* Firefox 19+ */
  color: red;
  font-family: FontAwesome;
  font-variant: small-caps;
}

.mandatory_field:-ms-input-placeholder {
  /* IE 10+ */
  color: red;
  font-family: FontAwesome;
  font-variant: small-caps;
}
Run Code Online (Sandbox Code Playgroud)
<link rel="stylesheet" href="https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css">

<input type="text" class="mandatory_field form-control" id="affiliation">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)