Javascript拖动效果函数
April/14th 2007

自己根据网上的一些代码资料写的拖动网页元素的代码

样例:  点击这里
 

function drag(o,s)
{
	if (typeof o == "string") o = document.getElementById(o);
	o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
	o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
	o.orig_index = o.style.zIndex;
		
	o.onmousedown = function(a)
	{
		this.style.cursor = "move";
		this.style.zIndex = 10000;
		var d=document;
		if(!a)a=window.event;
		var x = a.clientX+d.body.scrollLeft-o.offsetLeft;
		var y = a.clientY+d.body.scrollTop-o.offsetTop;
		//author: www.longbill.cn
		d.ondragstart = "return false;"
		d.onselectstart = "return false;"
		d.onselect = "document.selection.empty();"
				
		if(o.setCapture)
			o.setCapture();
		else if(window.captureEvents)
			window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);

		d.onmousemove = function(a)
		{
			if(!a)a=window.event;
			o.style.left = a.clientX+document.body.scrollLeft-x;
			o.style.top = a.clientY+document.body.scrollTop-y;
			o.orig_x = parseInt(o.style.left) - document.body.scrollLeft;
			o.orig_y = parseInt(o.style.top) - document.body.scrollTop;
		}

		d.onmouseup = function()
		{
			if(o.releaseCapture)
				o.releaseCapture();
			else if(window.captureEvents)
				window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
			d.onmousemove = null;
			d.onmouseup = null;
			d.ondragstart = null;
			d.onselectstart = null;
			d.onselect = null;
			o.style.cursor = "normal";
			o.style.zIndex = o.orig_index;
		}
	}
	
	if (s)
	{
		var orig_scroll = window.onscroll?window.onscroll:function (){};
		window.onscroll = function ()
		{
			orig_scroll();
			o.style.left = o.orig_x + document.body.scrollLeft;
			o.style.top = o.orig_y + document.body.scrollTop;
		}
	}
}


2996 read 7 comment(s)
#1
Guest   2008年03月26号 01:53       回复
太棒了 正在找这样的效果
#2
keeper   2008年06月15号 03:07       回复
可以考虑加个target容器的效果,类似igoogle
#3
Guest   2008年09月22号 18:22       回复
太棒了,我把这个改了一下,正用在一个项目中,其实可以在移动之后把被移动的div zindex设大一些,使被移动过的DIV处理顶层,效果会更好一些
#4
lujo   2008年10月22号 18:14       回复
唉,JS还得加强,多请教哈!
#5
walkingp   2009年10月19号 09:21       回复
hot dog
#6
宇博   2010年01月08号 14:51       回复
如果使用JQ制作应该会更简单,JQDNS居然就几行代码搞定拖动+调整大小
#7
longbill   2010年01月08号 15:03       回复
回复 宇博: 
恩,是的。。不过也要明白拖动的原理。  直接上手Jquery以后会出现很多问题的。
添加新的评论
称呼:*
邮件:*
网站:
内容:

Copyright © Longbill 2008-2024 , Designed by EndTo , Powered by EndCMS