[英]Retrieve a pseudo element's content property value using JavaScript
我有以下 jQuery 代碼:
$.each($(".coin"), function() {
var content = "/*:before content*/";
$("input", this).val(content);
});
我想根據其偽元素的content
屬性值( .coin:before
)使用 jQuery 更改每個輸入元素的值。
根據 MDN, .getComputedStyle()
方法的第二個參數是偽元素:
var style = window.getComputedStyle(element[, pseudoElt]);
pseudoElt(可選)- 指定要匹配的偽元素的字符串。 對於常規元素,必須省略(或 null)。
因此,您可以使用以下content
來獲取偽元素的content
值:
window.getComputedStyle(this, ':before').content;
$('.coin').each(function() {
var content = window.getComputedStyle(this, ':before').content;
$("input", this).val(content);
});
如果想根據字符獲取實體代碼,也可以使用以下方法:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.