简体   繁体   English

带字体真棒图标的JavaScript切换按钮

[英]JavaScript Toggle Button with Font Awesome Icon

I am new to the JavaScript world, and I'm attempting to learn how to use vanilla JS to program a button that will toggle its state between "play" and "pause." 我是JavaScript世界的新手,我正在尝试学习如何使用香草JS来编写一个按钮,该按钮将在“播放”和“暂停”之间切换其状态。 The issue I'm having is that I can verify in the console that my code is successfully toggling the class of the "i" tag, but the image doesn't seem to be updating. 我遇到的问题是,我可以在控制台中验证我的代码是否成功切换了“ i”标签的类,但是图像似乎没有更新。

Is this change not being reflected in the DOM tree somehow? 此更改是否以某种方式未反映在DOM树中?

HTML HTML

<a href="#" id="playBtn" class="btn btn-primary">
   <i class="fas fa-play" id="transportIcon"></i>
</a>

JS JS

var getBtn = document.getElementById('playBtn');
var getIcon = document.getElementById('transportIcon');

getBtn.addEventListener('click', function () {
    if (getIcon.className === 'fas fa-play') {
        getIcon.setAttribute('class', 'fas fa-pause');
    } else {
        getIcon.setAttribute('class', 'fas fa-play');
    }
});

there is working code example: 有工作代码示例:

 var getBtn = document.getElementById('playBtn'); var getIcon = document.getElementById('transportIcon'); getBtn.addEventListener('click', function () { if (getIcon.classList.contains('fa-play')) { getIcon.classList.remove('fa-play'); getIcon.classList.add('fa-pause'); } else { getIcon.classList.remove('fa-pause'); getIcon.classList.add('fa-play'); } }); 
 <a href="#" id="playBtn" class="btn btn-primary"> <i class="fas fa-play" id="transportIcon"></i> </a> 

I fixed this issue by using the non-SVG version of Font Awesome (4.7.0). 我通过使用非SVG版本的Font Awesome(4.7.0)解决了此问题。 That way, my JavaScript isn't fighting with FA's JS that controls the SVG icons they use in version 5. 这样,我的JavaScript就不会与控制它们在版本5中使用的SVG图标的FA的JS战斗。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM