CSS:active仅在单击期间起作用

时间:2019-05-09 12:00:10

标签: html css

当我单击星号时我想使其保持黄色,而当我再次单击时取消其颜色选择。

我尝试使用:active选项。

非常感谢您的帮助!

.fave {
    width: 70px;
    height: 50px;
    background: url(https://cssanimation.rocks/images/posts/steps/twitter_fave.png) no-repeat;
    background-position: 0 0;
    
}

.fave:hover {
    background-position: -3519px 0;
    transition: background 1s steps(55);
}
<div class="fave"></div>

4 个答案:

答案 0 :(得分:4)

如果您想仅使用js而不使用js,则可以使用复选框尝试此操作

[type="checkbox"]{
  display:none;
}
.fave {
    width: 70px;
    height: 50px;
    background: url(https://cssanimation.rocks/images/posts/steps/twitter_fave.png) no-repeat;
    background-position: 0 0;
    display: inline-block;
    
}

[type="checkbox"]:checked ~ .fave {
    background-position: -3519px 0;
    transition: background 1s steps(55);
}
<input type="checkbox" id="cb1">
<label class="fave" for="cb1"></label>

答案 1 :(得分:2)

:active表示同时按住鼠标按钮(或键)。

这不是切换状态。

CSS没有添加切换状态的机制。

为此,您将需要一个复选框(可以将其与:checked伪类结合使用)和/或JavaScript(具体取决于所要表达的语义)。

答案 2 :(得分:1)

我认为你想要这样的东西

jQuery(document).ready(function() {
  jQuery(".fave").click(function() {
    jQuery(this).toggleClass("active");
  })
})
.fave {
  width: 70px;
  height: 50px;
  background: url(https://cssanimation.rocks/images/posts/steps/twitter_fave.png) no-repeat;
  background-position: 0 0;
}

.fave:hover,
.fave.active {
  background-position: -3519px 0;
  transition: background 1s steps(55);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fave"></div>

答案 3 :(得分:0)

您只能通过JavaScript进行此操作。它可以使用:focus :active 伪元素制作CSS代码。但是,您只能在单击时设置颜色。如果要在单击时取消选择颜色,则必须通过js进行选择。我可以根据需要编写代码段。