You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS动画仅在第二次点击后生效的问题求助

问题:CSS过渡动画首次点击无效果,小球瞬间跳转

尝试用CSS过渡实现小球点击移动效果,设置动画时长1秒,但首次点击时小球直接跳到目标位置,后续点击可正常触发过渡动画。

问题原因

初始状态下,#ball的top和left属性未显式设置,浏览器默认值为auto。CSS过渡要求属性必须有明确的起始值与结束值才能计算动画过程,首次赋值时起始值为auto,无法触发过渡逻辑,因此小球直接跳转;首次赋值后top/left已有具体像素值,后续修改时即可正常计算过渡动画。

解决方案

页面加载时,给小球设置明确的top和left初始值,基于它的初始位置计算:

修改后的完整代码

<!DOCTYPE HTML>
<html>
<head>
<style>
#field {
    width: 200px;
    height: 200px;
    border: 10px groove black;
    background-color: green;
    cursor: pointer;
}

#ball {
    width: 40px;
    height: 40px;
    position: absolute;
    transition-property: top, left;
    transition-duration: 1s;
}
</style>
</head>
<body>
<div id="field">
<img src="https://en.js.cx/clipart/ball.svg" id="ball"> 
</div>

<script>
"use strict"

function moveElement(elem, x, y){
    if (elem.isConnected){
        let rect = elem.getBoundingClientRect();
        let rect2 = elem.parentElement.getBoundingClientRect();
        elem.style['top'] = y - rect.height/2 - parseInt(elem.parentElement.style['top']) + 'px';
        elem.style['left']= x - rect.width/2 - parseInt(elem.parentElement.style['left']) + 'px';
    } else {
        alert("No element");
    }
}

field.style['top']=300 + 'px';
field.style['left']=150 + 'px';
field.style['position']='absolute';
ball.style['position'] = 'absolute';

// 新增:设置小球初始的top和left明确值
const initialBallRect = ball.getBoundingClientRect();
ball.style.top = initialBallRect.top + 'px';
ball.style.left = initialBallRect.left + 'px';

field.onclick = (event) => {
    moveElement(ball, event.pageX, event.pageY);
}
</script>
</body>
</html>

关键修改点

在脚本初始化阶段,添加代码获取小球初始位置的坐标,并赋值给style.top和style.left,让CSS过渡有明确的起始值可以计算,确保首次点击也能触发过渡动画。

内容的提问来源于stack exchange,提问作者Andrey2020

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 23:50:19