问题
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="" />
</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", "");
});
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("")[0].data);
回答2:
You can try something like this:
$('.wrapper input:first').attr("placeholder", $('<textarea />').html("").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