问题
I have the following jQuery code:
$.each($(".coin"), function() {
var content = "/*:before content*/";
$("input", this).val(content);
});
I'd like to change the value of each input element using jQuery based on its pseudo element's content
property value (.coin:before
).
Here a example: http://jsfiddle.net/aledroner/s2mgd1mo/2/
回答1:
According to MDN, the second parameter to the .getComputedStyle() method is the pseudo element:
var style = window.getComputedStyle(element[, pseudoElt]);
pseudoElt (Optional) - A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.
Therefore you could use the following in order to get the pseudo element's content
value:
window.getComputedStyle(this, ':before').content;
Updated Example
$('.coin').each(function() {
var content = window.getComputedStyle(this, ':before').content;
$("input", this).val(content);
});
If you want to get the entity code based on the character, you can also use the following:
function getEntityFromCharacter(character) {
var hexCode = character.replace(/['"]/g, '').charCodeAt(0).toString(16).toUpperCase();
while (hexCode.length < 4) {
hexCode = '0' + hexCode;
}
return '\\' + hexCode + ';';
}
$('.coin').each(function() {
var content = window.getComputedStyle(this, ':before').content;
$('input', this).val(getEntityFromCharacter(content));
});
.dollar:before {
content: '\0024'
}
.yen:before {
content: '\00A5'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="coin dollar">
<input type="text" />
</div>
<div class="coin yen">
<input type="text" />
</div>
来源:https://stackoverflow.com/questions/34122243/retrieve-a-pseudo-elements-content-property-value-using-javascript