原有功能:拖拽,未实现z-index
补充功能:实现z-index
核心代码:
//代码请以运行框内为主,这里可能显示有错
/* --------------------------------------------------------------
* 程序名:拖拽区域块
* 修改者:草履虫
* email:caolvchong@gmail.com
* 主页:http://cceer.xmu.edu.cn/blog/
* 原始来源:http://bbs.blueidea.com/thread-2817125-1-1.html
* 增加功能:拖拽后的z-index设置
* Plus:有疑问或者建议请联系email
* --------------------------------------------------------------
*/
function move(id){
this.node = document.getElementById(id);
this.name = id;
this.node.style.cursor = "move";
this.zindex = parseInt(this.node.getAttribute("id").replace(/\D/g,""));
this.node.style.zIndex = this.zindex;
this.node.me = this;
this.node.onmousedown = this.mouse_down;
}
move.prototype.mouse_down = function(e){
e = window.event?window.event:e;
this.me.node.style.zIndex += 10000;// --->被修改了,原来100,现在10000
this.me.node.sub_x = e.clientX - this.me.node.offsetLeft;
this.me.node.sub_y = e.clientY - this.me.node.offsetTop;
this.me.node.onmousemove = this.me.mouse_move;
this.me.node.onmouseup = this.me.mouse_up;
}
move.prototype.mouse_move = function(e){
e = window.event?window.event:e;
this.me.node.style.cursor = "pointer";
this.me.node.style.left = e.clientX - this.me.node.sub_x + "px";
this.me.node.style.top = e.clientY - this.me.node.sub_y + "px";
this.me.node.onmouseup = this.me.mouse_up;
}
move.prototype.mouse_up = function(){
this.me.node.onmousemove = "";
this.me.node.style.cursor = "move";
this.me.node.style.zIndex = this.me.zindex; //还原被增加的z-index
var z_index = this.me.zindex ; //获取当前z-index
for(var i = 0; i < document.getElementsByTagName("div").length; i++){ //获取最大z-index
if(z_index < document.getElementsByTagName("div")[i].style.zIndex){
z_index = parseInt(document.getElementsByTagName("div")[i].style.zIndex);
}
}
this.me.node.style.zIndex = z_index + 1; //移动后的z-index,而不是还原
}
使用:
window.onload = function(){
new move("move1"); //你要拖拽的块的id,必须move开头,后面使用数字
new move("move2");
new move("move3");
}
运行:
提示:您可以先修改部分代码再运行