如何使用JavaScript为Fontawesome图标着色?

时间:2018-07-15 19:46:24

标签: javascript font-awesome

我有以下fa-icon

<div id="notification">
    <div id="info">
        <div class="service">
            <i class="fas fa-music"></i>
            <h1 class="name"></h1>
        </div>
    </div>
</div>

我尝试了以下方法以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;

但是他们都不起作用,我怎么能做到这一点?

编辑:它似乎仅在我的函数外部起作用,为什么在其内部不能起作用?

// 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
            });
        }
    }
}

3 个答案:

答案 0 :(得分:1)

由于5.0使用SVG try

document.querySelector('.fas fa-music').style.fill = Music;

如果这不起作用,则必须在其中选择SVG并在其中应用规则

答案 1 :(得分:0)

做类似

document.querySelector('.fa.fa-sign-in').style.color = "green"

您的选择器有误。对于您的情况,修改样式的正确行将是

document.querySelector('.fas.fa-music').style.color = "green"

将“绿色”更改为您的颜色

答案 2 :(得分:0)

您尝试了以下代码吗?

false

这也应该起作用:

document.querySelector('#info .service .fa-music').style.color = Music;

似乎您通过写document.querySelector('.fas.fa-music').style.color = Music; 犯了一个小错误。