CSS实现一个方块在页面中随机移动的效果

重点方法记录:

const boxPosition = box.getBoundingClientRect();

// 强制浏览器重新绘制元素并计算样式
box.style.setProperty('--top', `${boxPosition.top}px`);
box.style.setProperty('--left', `${boxPosition.left}px`);
void box.offsetWidth;
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>CSS位置动画示例</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            top: var(--top);
            left: var(--left);
            transition: top 1s ease-in-out, left 1s ease-in-out;
        }

        #move-btn {
            margin-top: 220px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <button id="move-btn">点击移动方块</button>

    <script>
        const box = document.querySelector('.box');
        const moveBtn = document.getElementById('move-btn');

        moveBtn.addEventListener('click', () => {
            const boxPosition = box.getBoundingClientRect();

            // 强制浏览器重新绘制元素并计算样式
            box.style.setProperty('--top', `${boxPosition.top}px`);
            box.style.setProperty('--left', `${boxPosition.left}px`);
            void box.offsetWidth;

            // 获取新的位置信息
            const newPosition = {
                top: Math.floor(Math.random() * (window.innerHeight - boxPosition.height)),
                left: Math.floor(Math.random() * (window.innerWidth - boxPosition.width))
            };
            box.style.setProperty('--top', `${newPosition.top}px`);
            box.style.setProperty('--left', `${newPosition.left}px`);
        });

    </script>
</body>

</html>