获取鼠标相对于浏览器窗口坐标

归来是少年 / 2023-08-16 / 原文

<!DOCTYPE html>
<html>
<head>
    <style>
        div {
            position: fixed;
            top: 10px;
            left: 10px;
            padding: 10px;
            background-color: #f1f1f1;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        const d = document.querySelector('div')
        document.addEventListener('mousemove', function (e) {
            let x = e.clientX
            let y = e.clientY
            d.innerHTML = `X: ${x}, Y: ${y}`

        })
    </script>
</body>

</html>

image