单击css中的图标时如何更改颜色

时间:2017-05-21 10:45:28

标签: jquery html css ajax

点击css和jquery中的图标心脏时,我正面临着变色的问题

的CSS:

尚未点击图标

.iconHeartInactive::before {
   content: '\e841';
   color: rgba(71,78,82,.4);
 }

点击图标时:

.iconHeartActive::after{
    content: '\e845';
    color: #ed1b77;
 }

HTML:

<span>
<button class="saveHome hoverPulse pan typeReversed">
    <span class="stackIcons">
        <i class="iconHeartActive iconOnly"></i>
        <i class="iconHeartEmpty typeReversed iconOnly"></i>
    </span>
</button>
</span> 
<script>
   $( "iconHeartInactive" ).click(function() {
   $( this ).toggleClass( "iconHeartActive" );
 });
 </script>

如何点击图标并改变颜色?非常感谢!

2 个答案:

答案 0 :(得分:1)

首先:将您的JS代码放在一个准备好的包装器中:

$(document).ready(function(){
  //your code here
});

第二:我们使用toggleClass来设置和取消设置对象的类,因此你有2个选项。 1-更改你的CSS所以在默认情况下它会获得你的非活动风格,当点击它时它会获得活跃的样式。 2-更改js以检查它是否具有活动类,因此基于您决定是否设置其中一个类的THAT语句。

因为您似乎不想更改样式:

<span>
<button class="saveHome hoverPulse pan typeReversed">
    <span class="stackIcons">
        <i class="iconHeartActive chosenHeartIcon iconOnly"></i>
        <i class="iconHeartEmpty typeReversed iconOnly"></i>
    </span>
</button>
</span> 
<script>
    $(document).ready(function(){
       $( ".chosenHeartIcon" ).click(function() {
        if($(this).hasClass('iconHeartActive')) {
            $( this ).removeClass( "iconHeartActive" );
            $( this ).addClass( "iconHeartInactive" );
        } else {
            $( this ).removeClass( "iconHeartInactive" );
            $( this ).addClass( "iconHeartActive" );
        }

     });
 });
 </script>

答案 1 :(得分:0)

1小提琴链接http://jsfiddle.net/JfGVE/2029/

<span>
<button class="saveHome hoverPulse pan typeReversed">
    <span class="stackIcons">
        <i class="iconHeartActive iconOnly"></i>
<i class="iconHeartEmpty typeReversed iconOnly"></i> 
    </span>
</button>
</span> 



//CSS Code

button{
  width: 100px;
  height: 50px;
  position: relative;
}

 .iconHeartEmpty::before{
   content: "\f001";
    font-family: FontAwesome;
    font-style: normal;
    font-weight: normal;
    text-decoration: inherit;
/*--adjust as necessary--*/
    color: #000;
    font-size: 18px;
    padding-right: 0.5em;
    position: absolute;
    top: 35%;
    left: 5%;
 }
 .iconHeartActive::after{
      content: "\f001";
    font-family: FontAwesome;
    font-style: normal;
    font-weight: normal;
    text-decoration: inherit;
/*--adjust as necessary--*/
    color: red;
    font-size: 18px;
    padding-right: 0.5em;
    position: absolute;
    top: 35%;
    left: 5%;
 }
 .hide{
   display: none;
 }



//Script

 $( ".saveHome" ).click(function() {
   $(".stackIcons i" ).toggleClass( "hide" );
 });