[英]How do I color a fontawesome icon with javascript?
I have the following fa-icon
: 我有以下fa-icon
:
<div id="notification">
<div id="info">
<div class="service">
<i class="fas fa-music"></i>
<h1 class="name"></h1>
</div>
</div>
</div>
I tried the following to color it with javascript: 我尝试了以下方法以javascript为其着色:
var Music = (swatches.DarkVibrant.getHex());
document.getElementById("info").getElementsByClassName("service")[0].style.color = Music;
// Gave i element this id
document.querySelector('#music').style.color = Music;
document.querySelector('.fas fa-music').style.color = Music;
However none of them work, how could I achieve this? 但是它们都不起作用,我怎么能做到这一点?
Edit: it seems like it only works outside my function, why does it not work when its inside? 编辑:好像它只在我的函数外部起作用,为什么当它在我的函数内部不起作用?
// Works
document.querySelector('.fas').style.color = "blue"
function mainUpdate(type) {
if (type == "music") {
if (isplaying) {
document.querySelector('.name').innerHTML = "Now playing";
document.querySelector('.details').innerHTML = "• " + album;
document.querySelector('.song').innerHTML = title;
document.querySelector('.artist').innerHTML = artist;
var milli = new Date().getMilliseconds();
var albumart = document.querySelector("#artworkImage");
albumart.src = "/var/mobile/Documents/Artwork.jpg?" + milli;
albumart.addEventListener('load', function () {
var vibrant = new Vibrant(albumart);
var swatches = vibrant.swatches()
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
var Name = (swatches.DarkVibrant.getHex());
var Music = (swatches.DarkVibrant.getHex());
}
document.querySelector('.name').style.color = Name; // Works
document.querySelector('.fas').style.color = "blue" // Doesnt work
});
}
}
}
Since 5.0 uses SVG try 由于5.0使用SVG请尝试
document.querySelector('.fas fa-music').style.fill = Music;
If this does not work then you will have to select SVG inside and apply rule in it 如果这不起作用,则必须在其中选择SVG并在其中应用规则
Do something like 做类似的事情
document.querySelector('.fa.fa-sign-in').style.color = "green"
You have a mistake in your selector. 您的选择器有误。 For your case, the correct line to modify the styles will be 对于您的情况,修改样式的正确行将是
document.querySelector('.fas.fa-music').style.color = "green"
Change "green" to your color 将“绿色”更改为您的颜色
Did you try the following code? 您是否尝试了以下代码?
document.querySelector('#info .service .fa-music').style.color = Music;
This one should also work: 这个也应该起作用:
document.querySelector('.fas.fa-music').style.color = Music;
It seems that you made a small mistake by writing ('.fas fa-music')
. 您似乎通过编写('.fas fa-music')
犯了一个小错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.