如何在用户单击对象时设置对象样式

时间:2015-05-12 14:54:16

标签: html css

在用于链接的css中,我可以在用户点击之前和用户点击之后设置样式。但是,如何为简单文本或用户单击该对象然后更改其颜色的对象执行此操作。 例如

<style>
.object:onmouseclick {
background-color:green;
padding:5px; 
}
</style>

我们必须写下onmouseclick

3 个答案:

答案 0 :(得分:0)

button:activebutton:focus可以解决问题。

a {
  background-color: red;
}

a:active {
  background-color: #efefef;
}
<a href="">myButton</a>

答案 1 :(得分:0)

如果您要设置链接样式,则可以使用:active:focus但是当您在dom元素上使用它时,您必须使用jQuery将类添加到单击的项目中通过该类应用该风格......

$('.object').click(function() {
  $(this).toggleClass('clicked');
});
.object {
  background-color: green;
  padding: 5px;
  cursor: pointer;
  width: 300px;
  color: orange;
}
.object.clicked {
  background-color: blue;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="object">
  <h1>The Mutants Are Revolting</h1>
  <p>Bender?! You stole the atom. That's the ONLY thing about being a slave. I am Singing Wind, Chief of the Martians. Anyhoo, your net-suits will allow you to experience Fry's worm infested bowels as if you were actually wriggling through them.</p>

</div>

答案 2 :(得分:0)

并可选择

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

.object{
   background:green;
   padding:5px; 
   width: 300px;
   height: 300px;
    position: relative;
}

input{
    display: none;
}
label{
    display: block;
    width: 300px;
    height: 300px;
}
input:checked ~ label{    
    position: absolute; top: 0; left: 0;
    width: 100%;
    height: 100%;
    background: #00f url(http://www.pubzi.com/f/sm-chess-horse.png) no-repeat center center;
    border: 1px solid #000;
}
<div class="object">
     <input type="checkbox" id="c1" name="checkbox" />  
        <label for="c1"></label>
</div>