如何实现Circle Div点击时向四周均匀扩展的动画效果?
实现圆形从中心均匀扩展收缩的动画效果
你的问题根源在于:只通过修改width和height实现缩放时,元素的定位锚点是左上角,所以会出现只往右下扩展的怪异效果。这里给你两种可行的解决方法,优先推荐第一种,更简洁高效:
方法一:使用 transform: scale()(推荐)
scale 变换默认以元素的中心点为原点进行缩放,完全不需要调整定位,是实现中心缩放最省心的方式。修改后的代码如下:
HTML
<div id="circle"></div>
CSS
#circle { width: 20px; height: 20px; background-color: black; position: absolute; top: 50%; left: 50%; border-radius: 50%; /* 可选:明确指定缩放原点,默认就是中心,可省略 */ transform-origin: center center; } .animate { animation: expand 1s forwards; } @keyframes expand { 0% { transform: scale(1); } 50% { transform: scale(2.5); } /* 对应20px→50px的缩放比例 */ 100% { transform: scale(1); } }
JavaScript
const circle = document.getElementById("circle"); circle.onclick = function() { circle.classList.add("animate"); // 绑定一次性事件,避免重复监听导致的异常 circle.addEventListener("animationend", function() { circle.classList.remove("animate"); }, { once: true }); };
关键说明
- 用
scale()替代修改宽高,自动保持中心位置,动画更流畅 - 将
animationend事件绑定到圆形元素本身,并用{ once: true }确保事件只触发一次,避免多次点击后出现逻辑混乱
方法二:调整定位偏移(兼容旧场景)
如果一定要通过修改width/height实现,可以在缩放时同步调整元素的偏移量,让中心保持不变:
@keyframes expand { 0% { width: 20px; height: 20px; transform: translate(0, 0); } 50% { width: 50px; height: 50px; /* 计算偏移:(目标尺寸-原尺寸)/2,往左上偏移抵消宽高增量 */ transform: translate(-15px, -15px); } 100% { width: 20px; height: 20px; transform: translate(0, 0); } }
原理是元素放大后,通过transform: translate把元素往左上移动,抵消宽高增加带来的偏移,从而保持中心位置不变。
内容的提问来源于stack exchange,提问作者Henry White
相关产品推荐
相关产品推荐

