Font awesome icon font as a placeholder in input after adding class with jquery

痴心易碎 提交于 2019-12-21 20:16:14

问题


I am trying to use font-awesome icons as a placeholder in search input field.

Jsfiddle examples

I use corresponding html entity as a placeholder, then use pseudo class to style placeholder with correct font-family (example 2 in jsfiddle):

HTML:

<div class="wrapper">
    <input class="icon" type="text" placeholder="&#61442;" />
</div>

CSS:

.wrapper {
    font-family:'arial', sans-serif;
}
input.icon {
    padding:5px;
}
input.icon::-webkit-input-placeholder {
    font-family:'FontAwesome';
}
input.icon::-moz-placeholder {
    font-family:'FontAwesome';
}
input.icon::-ms-input-placeholder {
    font-family:'FontAwesome';
}

It works as expected.

The problem starts when I try to add input class and placeholder via jquery (example 1 in jsfiddle):

JS:

$(document).ready(function() {
$('.wrapper input:first').addClass('icon');
$('.wrapper input:first').attr("placeholder", "&#61442;");
});

It doesn't apply font-family to input placeholder and just shows entity text instead.

I tried to mix things around and finally giving up. Please help!

Jsfiddle examples

P.S.: The rout of adding :before with font content to input wrapper in css will not work for my particular case.


回答1:


You should parse the hash first. You can use $.parseHTML:

$('.wrapper input:first').attr("placeholder",$.parseHTML("&#61442;")[0].data);



回答2:


You can try something like this:

$('.wrapper input:first').attr("placeholder", $('<textarea />').html("&#61442;").html());

JSFiddle

This works by passing the value as HTML instead of text, which can be achieved by creating a reference to an element which doesn't really exist.



来源:https://stackoverflow.com/questions/34842889/font-awesome-icon-font-as-a-placeholder-in-input-after-adding-class-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!