Font awesome icon font as a placeholder in input a

2019-04-12 16:31发布

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.

2条回答
Luminary・发光体
2楼-- · 2019-04-12 17:04

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.

查看更多
看我几分像从前
3楼-- · 2019-04-12 17:12

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

$('.wrapper input:first').attr("placeholder",$.parseHTML("&#61442;")[0].data);
查看更多
登录 后发表回答