js-事件1_获取鼠标坐标clientX+scrollLeft及兼容性写法_跟随鼠标移动的divs

原文链接:http://www.cnblogs.com/XChWaad/p/4913035.html

一、获取鼠标坐标

  clientX:鼠标到可视区边缘的距离;    scrollLeft:滚动条到页面顶端的距离(不可视区的距离)

  兼容性写法:

  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;

 

跟随鼠标移动的divs,代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <style>
        div {
            width: 10px;
            height: 10px;
            background: #F00;
            position: absolute;
        }
    </style>
    <script>
        window.onload = function () {
            document.onmousemove = function (ev) {
                var oEvent = ev || event;
                var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
                var oDivs = document.getElementsByTagName("div");

                oDivs[0].style.left = oEvent.clientX + scrollLeft + "px";
                oDivs[0].style.top = oEvent.clientY + scrollTop + "px";

                for (var i = oDivs.length - 1; i > 0; i--) {
                    oDivs[i].style.left = oDivs[i - 1].style.left;
                    oDivs[i].style.top = oDivs[i - 1].style.top;
                }
            }

        }
    </script>
</head>
<body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</body>
</html>

转载于:https://www.cnblogs.com/XChWaad/p/4913035.html

上一篇:Assert.isTrue 用法


下一篇:scrollLeft/scrollTop,offsetLeft/offsetTop,clientLeft/clientTop