多层div相互层叠激活方法(提升z-index)

最近有一个作业中的一个小功能要求以下:多层div相互层叠,要求激活其中一个。 先看我做的DEMO:http://xiebiji.com/works/activeDiv/ 来看一下关键的js代码(基于mootools):

//层叠激活
/*获取当前所有层区域*/
//定义一个存放多个区域数据的集合
var allArea=new Array();
//遍历所有存在的div
$$('#comm_area .comm_div').each(function(e){
	pushOneArea(e);//依次存数据
});
//往allArea集合中存入一个区域数据,e为$()方法得来的元素
function pushOneArea(e){
	var oneArea=new Object();//定义1个对象
	//赋予对象一些必要的数据
	oneArea.sx=e.getStyle('left').toInt();
	oneArea.ex=e.getStyle('left').toInt()+e.getStyle('width').toInt();
	oneArea.sy=e.getStyle('top').toInt();
	oneArea.ey=e.getStyle('top').toInt()+e.getStyle('height').toInt();
	oneArea.sq=e.getStyle('width').toInt()*e.getStyle('height').toInt();
	oneArea.el=e;//该对象对应的元素为传入的元素e
	allArea.push(oneArea);//追加数组元素
}
//为父层添加鼠标移动事件
$('comm_area').onmousemove=function(e){
	//初始化所有层状态
	$$('#comm_area .comm_div').setStyle('z-index',900);
	$$('#comm_area .comm_div').removeClass('focus');
	//开始激活,首先需要获取鼠标相对父层的坐标
	m=mPos(e);//获得鼠标窗口位置数据
	ol=this.parentNode.offsetLeft;//父层x方向偏移
	ot=this.parentNode.offsetTop;//父层y方向偏移
	nowX=m.X-ol;//相对的x坐标
	nowY=m.Y-ot-5;//相对的y坐标,-5是为了微调
	activeDiv(nowX,nowY);//激活
}
//激活鼠标所在位置层叠的所有div中面积最小的div(提升z-index)
function activeDiv(nowX,nowY){
	willActiveEl=null;//定义将要激活的元素
	minSq=null;//定义最小面积
	for(i=0;i<allArea.length;i++){
		//找出鼠标所在位置经过的所有层
		if(allArea[i].sx<nowX&&allArea[i].ex>nowX&&allArea[i].sy<nowY&&allArea[i].ey>nowY){
			//初始化第一个为面积最小,且为将要激活的元素
			if(minSq==null){
				minSq=allArea[i].sq;
				willActiveEl=allArea[i].el;
			}
			if(allArea[i].sq<minSq)
				willActiveEl=allArea[i].el;//获得最小面积的元素标为将要激活
		}
	}
	//假如找到元素
	if(willActiveEl!=null){
		willActiveEl.setStyle('z-index',9999);
		willActiveEl.addClass('focus');
	}
}
//获取当前鼠标所在位置
function mPos(e){
	mt=false;
	try{
		if(e.mt)mt=true;
	}catch(r){}
	if(mt)return e;
	e=e || window.event;
	if(e.pageX){
		xPos=e.pageX;
		yPos=e.pageY;
	} else { 
		xPos=e.clientX+document.documentElement.scrollLeft-document.body.clientLeft;
		yPos=e.clientY+document.documentElement.scrollTop-document.body.clientTop;
	}
	this.X=xPos;
	this.Y=yPos;
	return this;
}

整个思想就是:鼠标所在的位置下面所有层叠中的DIV中面积最小的层就是要激活的层(当然这个思路还得再斟酌一下,有想法的同学欢迎发表评论) 该效果虽然引进了mootools框架,但是实际上该效果没有用到mootools一些特殊的类,用到的都是一些基本的方法(如:获取元素集、遍历之类的)。 www.flickr.com的图注评论也有做这种激活的效果,但是我不知道它是什么原理的,希望大家有更好的方法。

No Response to 多层div相互层叠激活方法(提升z-i... »

还没有任何评论。

Leave a Reply

Email address is not published

You should say a Chinese word to pass spam check. If you can not input Chinese, just copy 你好 and paste them into comment text box.