美文网首页
js 鼠标跟随

js 鼠标跟随

作者: lucky_yao | 来源:发表于2020-10-05 08:06 被阅读0次

1: offsetLeft 获取元素到左边的距离

    offsetTop   获取元素到上边的距离

    offsetWidth 获取元素的宽

    offsetHeight    获取元素的高

2: document.documentElement.clientWidth 获取可视窗口的宽度

document.documentElement.clientHeight     获取可视窗口的高度

Element.clientWidth

Element.clientHeight

3: scrollLeft 横滚动条的值

scrollTop   竖滚动条的值
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            div {
                width: 20px;
                height: 20px;
                background: #008000;
                position: absolute;
            }
        </style>
    </head>
    <body>
        <div></div>
    </body>
    <script type="text/javascript">
        var odiv = document.getElementsByTagName('div')[0];
        window.onmousemove = function(e) {
            var e = e || window.event;
            l = e.clientX - odiv.offsetWidth / 2;
            t = e.clientY - odiv.offsetHeight / 2;
            if (l < 0) {
                l = 0;
            }
            if (t < 0) {
                t = 0;
            }
            if (l > document.documentElement.clientWidth - odiv.offsetWidth) {
                l = document.documentElement.clientWidth - odiv.offsetWidth
            }
            if (t > document.documentElement.clientHeight - odiv.offsetHeight) {
                t = document.documentElement.clientHeight - odiv.offsetHeight
            }
            odiv.style.left = l + 'px';
            odiv.style.top = t + 'px';
        }
    </script>
</html>

相关文章

网友评论

      本文标题:js 鼠标跟随

      本文链接:https://www.haomeiwen.com/subject/nqbhyktx.html