从类名访问FontAwesome unicode

时间:2017-04-21 13:31:16

标签: javascript jquery unicode

在检查元素时,请说我有这个HTML。

<i class="fa fa-user">
   ::before
</i>

CSS:

.fa-user::before {
    content: "\f007";
}

我在这里获取fa-user的内容

    $('.fa-user').each(function(){
        var unicode = window.getComputedStyle(this,':before').content;
        console.log(unicode);
    });

问题是unicode变量呈现为图标(符号)。

enter image description here

我希望它是字符串 - &gt; &#34; \ F007&#34;

我也试过这个,但它只返回一些不相关的数字,在这种情况下它的数字是22

var unicode = window.getComputedStyle(this,':before').content.charCodeAt(0).toString(16);

1 个答案:

答案 0 :(得分:5)

某些浏览器将.content值包含引号(see here)。在获得第一个字符之前,您需要删除它们:

$('.fa-user').each(function() {
  var unicode = window.getComputedStyle(this, ':before').content
                                                        .replace(/'|"/g, '') // <-----
                                                        .charCodeAt(0)
                                                        .toString(16);
  console.log("\\" + unicode);
});
.fa-user::before { content: "\f007"; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<i class="fa fa-user"></i>