码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-10-27 01:45:12      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

一、获取鼠标坐标

  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>

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

标签:

原文地址:http://www.cnblogs.com/XChWaad/p/4913035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!