码迷,mamicode.com
首页 > 编程语言 > 详细

javascript——拖拽函数封装

时间:2015-03-30 18:01:36      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

CSS部分:

#div1{ width: 100px; height: 100px; background: #ccc; position: absolute;}
#img1{ position: absolute;}

HTML部分:

<div id="div1"></div>
<img id="img1" src="img/1.jpg" />

JS部分:

window.onload = function(){
        //获取相关元素
        var oDiv = document.getElementById(‘div1‘);
        var oImg = document.getElementById(‘img1‘);

        //函数调用
        drag(oDiv);
        drag(oImg);

        //函数封装
        function drag(obj){
            //obj鼠标按下
            obj.onmousedown = function(ev){

                var ev = ev || event;

                var disX = ev.clientX - this.offsetLeft;
                var disY = ev.clientY - this.offsetTop;

                if(obj.setCapture){
                    obj.setCapture();
                }
                
                //obj鼠标移动
                document.onmousemove = function(ev){

                    var ev = ev || event;

                    obj.style.left = ev.clientX - disX + ‘px‘;
                    obj.style.top = ev.clientY - disY + ‘px‘;
                };

                //obj鼠标释放
                document.onmouseup = function(){
                    document.onmousemove = document.onmouseup = null;
                    if(obj.releaseCapture){
                        obj.releaseCapture();
                    }
                }
                return false;
            };
        };
    };

 

javascript——拖拽函数封装

标签:

原文地址:http://www.cnblogs.com/bokebi520/p/4378653.html

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