简体   繁体   English

单击更改Fontawesome图标不起作用

[英]Changing fontawesome icon on click not working

I have a 'volume' icon that will mute sounds when clicked, and unmute when clicked again. 我有一个“音量”图标,当单击该按钮时,它将使声音静音,而再次单击时,则将其静音。 I used .addClass() and .removeClass() to toggle between icon classes. 我使用.addClass()和.removeClass()在图标类之间切换。 While I am able to change from "fa-volume-up" to "fa-volume-off", I cannot do the reverse; 虽然我可以从“ fa-volume-up”更改为“ fa-volume-off”,但我不能相反。 for some reason it's not passing the "else if" condition after the icon has changed to 'volume-off'. 由于某种原因,在图标更改为“关闭音量”后,它没有通过“ else if”条件。

I want to change the icon from 'fa-volume-up' to 'fa-volume-off'. 我想将图标从“ fa-volume-up”更改为“ fa-volume-off”。

 // index.js $(function() { $('#vol-btn').on('click', function() { if ($(this).hasClass('fa-volume-up')) { $(this).removeClass('fa-volume-up').addClass('fa-volume-off'); //sound.mute(true); console.log("Muting sound.") // it won't enter this condition! } else if ($(this).hasClass('fa-volume-off')) { $(this).removeClass('fa-volume-off').addClass('fa-volume-up'); //sound.mute(false); console.log("Unmuting sound.") } }); }) 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <!--index.html --> <div class='btns'> <i id='vol-btn' class="fa fa-volume-up"></i> </div> 

I agree with @Derek that toggling the icon makes more sense - then using the class to determine the console.log message (which I am doing in a ternary operator). 我同意@Derek的观点,即切换图标更有意义-然后使用该类确定console.log消息(这是我在三元运算符中所做的)。

 // index.js $(function() { $('#vol-btn').on('click', function() { $(this).toggleClass('fa-volume-up fa-volume-off') $(this).hasClass('fa-volume-off') ? console.log('Muting sound') : console.log('Unmuting Sound') }) }) 
 #vol-btn:hover { cursor: pointer; } 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <!--index.html --> <div class='btns'> <i id='vol-btn' class="fa fa-volume-up fa-2x"></i> </div> 

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

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