JS简单实现拖拽可视化构图

简易实现JS拖拽构图:

提供两个js函数,调用run()函数即可实现效果:


		/**
			* String targetId 第一个参数为目标容器的id属性值
			* String componentClass 第二个参数为拖拽组件的class属性值
		*/
		function run(targetId,componentClass){
			
			var component =  document.getElementsByClassName(componentClass);
			for(var c in component){
				if(isNaN(c)){
					continue;
				}

				drag(component[c],document.getElementById(targetId));
			}
			
		}

		function drag(component,target){
			component.onmousedown = function(e){

				var diffW = e.clientX - this.offsetLeft , diffH = e.clientY - this.offsetTop;
				var clo = document.createElement('div');
				clo = this.cloneNode(true);

				clo.style.filter = "alpha(opacity=30)";
				clo.style.opacity = 0.3;
				clo.style.float = "left";
				clo.style.position = "absolute";
				clo.style.top = this.offsetTop +'px';
				clo.style.left = this.offsetLeft +'px';
				
				document.body.onmousemove = function(e){
					var e = e || window.event;

					clo.style.top = (e.clientY - diffH) + 'px';
					clo.style.left = (e.clientX - diffW) + 'px';
				}
				document.body.onmouseup = function(){
					document.body.onmousemove = null;
					var tl = target.offsetLeft , tt = target.offsetTop , tw = target.offsetWidth , th = target.offsetHeight;
					var ml = clo.offsetLeft , mt = clo.offsetTop , mw = clo.offsetWidth , mh = clo.offsetHeight;

					if(tl < ml+mw && tl + tw > ml && tt < mt + mh && tt + th > mt){
						clo.style.top = mt - tt + 'px';
						clo.style.left = ml - tl + 'px';
						clo.style.filter = "alpha(opacity=100)";
						clo.style.opacity = 1;
						target.style.position = 'relative';
						target.style.overflow = "hidden";
						target.appendChild(clo);
					}else{
						clo.remove();
					}
					document.body.onmouseup = null;
				}

				document.body.appendChild(clo);

			}
			
		}

完成后,目标容器的内部HTML即为最终构图。

当然,这是比较简易的,只是给出一个简单的原理和基本的功能。

下面提供一个HTML的demo:

 
  
 
  



	
	Document
	


	
0
1
2
3
4
5
6
7
8
9
 即可实现拖拽构图。 
  

你可能感兴趣的:(JS)