Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

jquery - Retrieve a pseudo element's content property value using JavaScript

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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: '024'
}
.yen:before {
  content: '0A5'
}
<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...