一个躲避鼠标的按钮

写了一个有趣的小组件,只要鼠标箭头一靠近就会躲避

效果
在这里插入图片描述
完整代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>dodge-button</title>

    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        button {
            background-color: blue;
            border: none;
            color: white;
            padding: 1rem 2rem;
            border-radius: 4px;
            transform-style: preserve-3d;
        }
    </style>
</head>

<body>
    <button id="button">点不到</button>

    <script>
        const button = document.getElementById('button')

        const distanceBetween = (p1x, p1y, p2x, p2y) => {
            const dx = p1x - p2x
            const dy = p1y - p2y
            return Math.sqrt(dx * dx + dy * dy)
        }

        const bx = button.parentNode.offsetLeft +
            button.offsetLeft +
            button.offsetWidth / 2

        const by = button.parentNode.offsetTop +
            button.offsetTop + button.offsetHeight / 2

        document.addEventListener('mousemove', event => {
            const radius = Math.max(
                button.offsetWidth * 0.75,
                button.offsetHeight * 0.75,
                100
            )

            const dist = distanceBetween(event.clientX, event.clientY, bx, by)
            const angle = Math.atan2(event.clientY - by, event.clientX - bx)

            const ox = -1 * Math.cos(angle) * Math.max(radius - dist, 0)
            const oy = -1 * Math.sin(angle) * Math.max(radius - dist, 0)

            const rx = oy /2
            const ry = -ox /2

            button.style.transition = `all 0.1s ease`
            button.style.transform = `translate(${ox}px, ${oy}px) rotateX(${rx}deg) rotateY(${ry}deg)`
            button.style.boxShadow = `0px ${Math.abs(oy)}px ${(Math.abs(oy) / radius) * 40}px rgba(0,0,0,.15)`
        })
    </script>
</body>

</html>
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值