从中心用颜色填充圆形Div

Fill Circle-Shaped Div From Center with Color On Click

本文关键字:Div 填充 颜色      更新时间:2023-09-26

我有一个圆形的div, class=" complete-button" (height/width =27px, border radius = 12px)。我想在点击时改变这个div的背景颜色,从中心开始,用温和的放松向外扩展。

做这件事最有效的方法是什么?我已经看到一些帖子使用css on-hover(使用前后选择器)实现了这一点,但我还没有足够的悟性将这个想法转化为jQuery on-click。任何帮助将非常感激!

使用以下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%;
}

然后切换selected类点击。

$('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>

你可以在css中定义你的过渡效果,并使用js来执行简单的类切换。

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