JS实现div随着鼠标移动

来源:互联网 发布:一览 mac 编辑:程序博客网 时间:2024/05/16 19:28

效果图

这里写图片描述

代码

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <div id="rec" style="position:absolute;left: 100px;top: 100px; width: 50px;height: 50px;background: red;"></div>    </body>    <script type="text/javascript">        //获取div元素    var rec = document.getElementById("rec")    var down = false;    var dx = 0;    var dy = 0;    var sx = 0;    var sy = 0;    document.onmousemove = function(e){        if (down) {            var ev = e || event;            console.log(ev.clientY)            rec.style.top = ev.clientY - (dy - sy) + 'px';            rec.style.left = ev.clientX - (dx - sx) + 'px';        }    }    rec.onmousedown = function(){        dx = event.clientX;        dy = event.clientY;        sx = parseInt(rec.style.left);        sy = parseInt(rec.style.top);        if (!down) {            down  = true;        }    }    document.onmouseup = function(){        if (down) {            down = false;        }    }    </script>    <script></html>
这里写代码片

在上面的代码中我们需要注意下面几个地方:
1.事件兼容
在ie中我们通过window.event对象就能获取到事件对象,而在火狐中,事件对象是通过函数的参数传递过来的,所以在此我们要进行一个判断,clientX指的是鼠标在当前浏览器窗口中的位置。

2.clientX返回的是一个数字,我们需要拼接px,才能出现效果。

3.需要给div指定定位方式,使其脱离文档流,才能起到移动的效果

完成了上面的功能之后,我们来实现一下点击动态创建div,然后移动

效果图

这里写图片描述

代码

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>        <style type="text/css">            .one{                position: absolute;            }        </style>    </head>    <body>        <input type="button" id="btn" value="add" />    </body>    <script type="text/javascript">    var btn = document.getElementById('btn');    var down = false;    var dx = 0;    var dy = 0;    var sx = 0;    var sy = 0;    var d= null;    btn.onclick = function() {        if (d != null) {            return;        }        d = document.createElement('div');        //d.style.left要带px        d.style.left = "100px";        d.style.top = "40px";        d.style.background = "green";        d.style.width = "100px";        d.style.height = "30px"        d.className = "one";        document.body.appendChild(d)        //此处的onmousedown事件要放在click函数中,否则会报错        d.onmousedown = function(){            dx = event.clientX;            dy = event.clientY;            sx = parseInt(d.style.left);            sy = parseInt(d.style.top);            if (!down) {                down  = true;            }        }    }        document.onmousemove = function(e){            if (down) {                var ev = e || event;                d.style.top = ev.clientY - (dy - sy) + 'px';                d.style.left = ev.clientX - (dx - sx) + 'px';            }        }        document.onmouseup = function(){            if (down) {                down = false;            }        }    </script></html>