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

跟谁鼠标移动

时间:2016-08-01 22:47:25      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 100px; height: 100px; background: red; position: absolute;}
</style>
<script>
window.onload = function() {
    
    /*
    onmousedown : 选择元素
    onmousemove : 移动元素
    onmouseup     : 释放元素
    */
    var oDiv = document.getElementById(div1);
    oDiv.onmousedown = function(ev) {
        var ev = ev || event;
        var disX = ev.clientX - this.offsetLeft;
        var disY = ev.clientY - this.offsetTop;
        //onmousemove在onmousedown之后,所以可以写在里面。        //不用oDiv.onmousemove是因为防止鼠标移除div就不会有移动事件了,div的鼠标移动会冒泡到document,
        document.onmousemove = function(ev) {
            var ev = ev || event;    
            oDiv.style.left = ev.clientX - disX + px;
            oDiv.style.top = ev.clientY - disY + px;
        }
        document.onmouseup = function() {
            document.onmousemove = document.onmouseup = null;
        }
    }
}
</script>
</head>

<body>
    <div id="div1">
    </div>
    <div style="width: 100px; height: 100px; background: green; position: absolute; left: 400px; top: 200px;">
    </div>
</body>
</html>

 

跟谁鼠标移动

标签:

原文地址:http://www.cnblogs.com/yaowen/p/5727429.html

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