Fill Circle-Shaped Div From Center with Color On C

2019-09-03 12:33发布

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条回答
一纸荒年 Trace。
2楼-- · 2019-09-03 13:12

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>

查看更多
Juvenile、少年°
3楼-- · 2019-09-03 13:15

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');
  });

})();
查看更多
登录 后发表回答