JavaScript拖拽 1.0

这两天没什么心情,进步不大,心虚。刚搞了个简单的拖拽,试了下,IE 8.0, Firefox都可以

var drag = {
    enable : function(domIdStr){
        var dom = document.getElementById(domIdStr);
        var diffX = 0, diffY = 0, draging = false;
        dom.style.position = 'absolute';
        dom.style.visibility = 'visible';
        dom.style.width = '200px';
        dom.style.height = '100px';
        dom.style.backgroundColor = 'teal';
        
        dom.onmousedown = function(e){
            e = e || window.event;
            draging = true;
            dom.style.cursor = 'move';
			diffX = e.clientX - dom.offsetLeft;
			diffY = e.clientY - dom.offsetTop;
			if(dom.setCapture){
			    dom.setCapture();
			}
			dom.onmousemove = function(e){
                e = e || window.event;
		        if(draging){
        	        dom.style.left = (e.clientX - diffX) + 'px';
        	        dom.style.top = (e.clientY - diffY) + 'px';
		        }
            };
	        dom.onmouseup = function(e){
		        e = e || window.event;
		        if(dom.releaseCapture){
		            dom.releaseCapture();
		        }
		        draging = false;
		        dom.style.cursor = 'default';
		        dom.onmousemove = null;
		        dom.onmouseup = null;
		        
	        };
        };
    }
};

 稍作修改,再出个1.1版本,就不发新的blog了

 

var drag = {
    enable : function(domIdStr, titleDomIdStr){
        var dom = document.getElementById(domIdStr);
        var title = document.getElementById(titleDomIdStr);
        var diffX = 0, diffY = 0, draging = false;
        dom.style.position = 'absolute';
        dom.style.visibility = 'visible';
        dom.style.width = '200px';
        dom.style.height = '100px';
        dom.style.backgroundColor = 'teal';
        
        title.onmousedown = function(e){
            e = e || window.event;
            draging = true;
            title.style.cursor = 'move';
            title.style.margin = 0;
            title.style.border = '1px solid yellow';
			diffX = e.clientX - dom.offsetLeft;
			diffY = e.clientY - dom.offsetTop;
			if(title.setCapture){
			    title.setCapture();
			}
			title.onmousemove = function(e){
                e = e || window.event;
		        if(draging){
        	        dom.style.left = (e.clientX - diffX) + 'px';
        	        dom.style.top = (e.clientY - diffY) + 'px';
		        }
            };
	        title.onmouseup = function(e){
		        e = e || window.event;
		        if(title.releaseCapture){
		            title.releaseCapture();
		        }
		        draging = false;
		        title.style.cursor = 'default';
		        title.onmousemove = null;
		        title.onmouseup = null;
		        
	        };
        };
    }
};

  

 

posted @ 2011-10-27 22:42  realwall  阅读(182)  评论(0编辑  收藏  举报