<!DOCTYPE html>
<html>
<head>
    <title>创建带有圆角动画和可拖动功能的浮动 Div</title>
    <style>
        .floating-div {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 300px;
            height: 200px;
            background-color: #ffffff;
            border-radius: 10px;
            box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
            cursor: move;
            animation: floatAnimation 3s infinite;
        }
<pre><code>    @keyframes floatAnimation {
        0% {
            transform: translate(-50%, -50%);
        }
        50% {
            transform: translate(-50%, -45%);
        }
        100% {
            transform: translate(-50%, -50%);
        }
    }
&lt;/style&gt;
&lt;script&gt;
    window.addEventListener('DOMContentLoaded', (event) =&gt; {
        const div = document.querySelector('.floating-div');

        let isDragging = false;
        let offset = [0, 0];

        div.addEventListener('mousedown', (e) =&gt; {
            isDragging = true;
            offset = [
                div.offsetLeft - e.clientX,
                div.offsetTop - e.clientY
            ];
        });

        document.addEventListener('mouseup', (e) =&gt; {
            isDragging = false;
        });

        document.addEventListener('mousemove', (e) =&gt; {
            e.preventDefault();
            if (isDragging) {
                div.style.left = (e.clientX + offset[0]) + 'px';
                div.style.top = (e.clientY + offset[1]) + 'px';
            }
        });
    });
&lt;/script&gt;
</code></pre>
</head>
<body>
    <div class='floating-div'></div>
</body>
</html>
创建带有圆角动画和可拖动功能的浮动 Div

原文地址: https://www.cveoy.top/t/topic/qiKN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录