Fill Circle-Shaped Div From Center with Color On Click

时间:2016-10-20 19:32:36

标签: javascript jquery html css css3

I have a "circular-shaped" div with class = "complete-button" (height/width =27px, border radius = 12px). I'd like to change the background color of this div on-click, starting from the center and expanding outwards with a gentle easing.

What's the most efficient approach for doing this? I've seen some posts accomplishing this using css on-hover (using before and after selectors), but I'm not yet savvy enough to convert that idea to a jQuery on-click. Any help would be greatly appreciated!

2 个答案:

答案 0 :(得分:2)

Use this CSS:

div.button:after {
  content: '';                 /* needed for rendering */
  position: relative;          
  display: block;              /* so we can set width and height */
  border-radius: 50%;
  height: 0%;
  width: 0%;
  margin: auto;                /* center horizontally */
  background: red;
  top: 50%;                    /* center vertically */
  transform: translateY(-50%); /* center vertically */
  transition: 1s;
}

div.button.selected:after {
  height: 100%;
  width: 100%;
}

Then toggle the selected class on click.

Snippet

$('div').click(function() {
  $(this).toggleClass('selected');
});
div.button {
  height: 27px;
  width: 27px;
  border-radius: 50%;
  background: green;
}

div.button:after {
  content: '';                 /* needed for rendering */
  position: relative;          
  display: block;              /* so we can set width and height */
  border-radius: 50%;
  height: 0%;
  width: 0%;
  margin: auto;                /* center horizontally */
  background: red;
  top: 50%;                    /* center vertically */
  transform: translateY(-50%); /* center vertically */
  transition: 1s;
}

div.button.selected:after {
  height: 100%;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">

</div>

答案 1 :(得分:0)

You define your transition effects in css, and use js to perform simple class toggle.

Play with it on codepen

html:

<button class="myButton">My Button</button>

css:

.myButton{
  margin-left:auto;
  margin-right: auto;
  display: block;

  transition: background-color,height,width 0.5s ease;

  background-color: red;
  height: 100px;
  width: 100px;
  border-radius: 49px;

}

.myButton.on{
  background-color: yellow;
  height: 120px;
  width: 120px;
  border-radius: 59px;
}

JS:

$(function(){

  $('.myButton').click(function(){
    $(this).toggleClass('on');
  });

})();