JS拖动层的实现原理

简介: 解决思路      这个效果并不算常见,通常用于游戏或个人站点中。因为拖曳是靠鼠标来操作的,所以对鼠标的位置的捕获是问题的重点,然后才是根据鼠标的位置设置层的位置。 具体步骤: 1.在对象(层)上按下鼠标时,先捕获到需要拖曳的对象,然后获取或设置该对象的相关属性。

解决思路
    
这个效果并不算常见,通常用于游戏或个人站点中。因为拖曳是靠鼠标来操作的,所以对鼠标的位置的捕获是问题的重点,然后才是根据鼠标的位置设置层的位置。

具体步骤
1.在对象(层)上按下鼠标时,先捕获到需要拖曳的对象,然后获取或设置该对象的相关属性。
obj=event.srcElement
obj.setCapture()
z=obj.style.zIndex
obj.style.zIndex=100
x=event.offsetX
y=event.offsetY
down=true

2.开始拖曳时,捕获鼠标当前位置,并根据该数值设置被拖曳对象的位置。

obj.style.posLeft=document.body.scrollLeft+event.x-x
obj.style.posTop=document.body.scrollTop+event.y-y

3.拖曳完松开鼠标后,重设标志 down ,还原对象的 z-index并释放对它的鼠标捕捉。

down=false  
obj.style.zIndex=z  
obj.releaseCapture()

4.完整代码。

<script>
var x,y,z,down=false,obj    
function init(){
obj=event.srcElement      //事件触发对象
obj.setCapture()             //设置属于当前对象的鼠标捕捉
z=obj.style.zIndex           //获取对象的z轴坐标值
//设置对象的z轴坐标值为100,确保当前层显示在最前面
obj.style.zIndex=100
x=event.offsetX    //获取鼠标指针位置相对于触发事件的对象的X坐标
y=event.offsetY    //获取鼠标指针位置相对于触发事件的对象的Y坐标
down=true          //布尔值,判断鼠标是否已按下,true为按下,false为未按下
}

function moveit(){
//判断鼠标已被按下且onmouseover和onmousedown事件发生在同一对象上
if(down&&event.srcElement==obj){
    with(obj.style){
/*设置对象的X坐标值为文档在X轴方向上的滚动距离加上当前鼠标指针相当于文档对象的X坐标值减鼠标按下时指针位置相对于触发事件的对象的X坐标*/

         posLeft=document.body.scrollLeft+event.x-x
/*设置对象的Y坐标值为文档在Y轴方向上的滚动距离加上当前鼠标指针相当于文档对象的Y坐标值减鼠标按下时指针位置相对于触发事件的对象的Y坐标*/
         posTop=document.body.scrollTop+event.y-y
    }
}
}

function stopdrag(){
//onmouseup事件触发时说明鼠标已经松开,所以设置down变量值为false
down=false  
obj.style.zIndex=z        //还原对象的Z轴坐标值
obj.releaseCapture() //释放当前对象的鼠标捕捉
}
</script>

<div onmousedown=init() onmousemove=moveit() onmouseup=stopdrag() style="position:absolute;left:20;top:190;width:100;height:150;border:1px solid #000000;z-index:1;background:#eeeeee">Layer 1</div>
<div onmousedown=init() onmousemove=moveit() onmouseup=stopdrag() style="position:absolute;left:60;top:10;width:100;height:150;border:1px solid #000000;z-index:2;background:#eeeeee">Layer 2</div>
<div onmousedown=init() onmousemove=moveit() onmouseup=stopdrag() style="position:absolute;left:100;top:90;width:100;height:150;border:1px solid #000000;z-index:3;background:#eeeeee">Layer 3</div>

注意:只有 CSS 的 position 属性值为 absolute 的对象才能进行拖动操作。
提示:如果需要将拖曳组件化,可以参考第二部分HTC一节。
技巧:可以在 init() 函数中加一句 event.cancelBubble=true ,以取消在该对象上的事件冒泡。
试一试:读者可以试着实现移动其他对象,例如移动一个图片或文本框。
特别提示
在拖曳对象前必须确保该对象的为绝对定位的,把上面的完整代码保存就可以看到效果了,在实际就用时务必在对象上加上 onmousedown、onmousemove和onmouseup三个事件并触发相应函数。代码运行效果如图 3.8 所示。

图 3.8 可拖动的层

特别说明


本例需要掌握的技巧比较多,捕捉鼠标,获取鼠标位置(相当于对象),释放鼠标捕捉,文档的滚动距离还有with 语句。
1.        setCapture() 设置属于当前文档的对象的鼠标捕捉。
2.        event.offsetX 设置或获取鼠标指针位置相对于触发事件的对象的 x 坐标。
3.        event.offsetY 设置或获取鼠标指针位置相对于触发事件的对象的 y 坐标。
4.        releaseCapture() 释放当前文档中对象的鼠标捕捉。
5.        scrollLeft 设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离。
6.        scrollTop 设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离。
7.        with 为一个或多个语句设定默认对象。

以下这个方法做出来的比较好看,并增加了层的几个功能
3个不同高度的三维可拖动图层的例子
=====================================================================

<html>
<head>
<title>_xWin</title>
<style type='text/css'>
<!--
a:visited{text-decoration:none;color:slategray;}
a:hover{text-decoration:underline;color:slategray;}
a:link{text-decoration:none;color:slategray;}
-->
</style>
<script language=JScript>
<!--
//
可以打包为js文件;
var x0=0,y0=0,x1=0,y1=0;
var offx=6,offy=6;
var moveable=false;
var hover='orange',normal='slategray';//color;
var index=10000;//z-index;
//开始拖动;
function startDrag(obj)
{
//锁定标题栏;
obj.setCapture();
//定义对象;
var win = obj.parentNode;
var sha = win.nextSibling;
//记录鼠标和层位置;
x0 = event.clientX;
y0 = event.clientY;
x1 = parseInt(win.style.left);
y1 = parseInt(win.style.top);
//记录颜色;
normal = obj.style.backgroundColor;
//改变风格;
obj.style.backgroundColor = hover;
win.style.borderColor = hover;
obj.nextSibling.style.color = hover;
sha.style.left = x1 + offx;
sha.style.top = y1 + offy;
moveable = true;
}
//拖动;
function drag(obj)
{
var win = obj.parentNode;
var sha = win.nextSibling;
if(moveable)
{
win.style.left = x1 + event.clientX - x0;
win.style.top = y1 + event.clientY - y0;
sha.style.left = parseInt(win.style.left) + offx;
sha.style.top = parseInt(win.style.top) + offy;
}
}
//停止拖动;
function stopDrag(obj)
{
var win = obj.parentNode;
var sha = win.nextSibling;
win.style.borderColor = normal;
obj.style.backgroundColor = normal;
obj.nextSibling.style.color = normal;
sha.style.left = obj.parentNode.style.left;
sha.style.top = obj.parentNode.style.top;
//放开标题栏;
obj.releaseCapture();
moveable = false;
}
//获得焦点;
function getFocus(obj)
{
index = index + 2;
var idx = index;
obj.style.zIndex=idx;
obj.nextSibling.style.zIndex=idx-1;
}
function min(obj)
{
var win = obj.parentNode.parentNode;
var sha = win.nextSibling;
var tit = obj.parentNode;
var msg = tit.nextSibling;
var flg = msg.style.display=="none";
if(flg)
{
win.style.height = parseInt(msg.style.height) + parseInt(tit.style.height) + 2*2;
sha.style.height = win.style.height;
msg.style.display = "block";
obj.innerHTML = "0";
}
else
{
win.style.height = parseInt(tit.style.height) + 2*2;
sha.style.height = win.style.height;
obj.innerHTML = "2";
msg.style.display = "none";
}
}
function cls(obj)
{
var win = obj.parentNode.parentNode;
var sha = win.nextSibling;
win.style.visibility = "hidden";
sha.style.visibility = "hidden";
}
//创建一个对象;
function xWin(id,w,h,l,t,tit,msg)
{
index = index+2;
this.id    = id;
this.width   = w;
this.height = h;
this.left   = l;
this.top    = t;
this.zIndex = index;
this.title   = tit;
this.message = msg;
this.obj    = null;
this.bulid   = bulid;
this.bulid();
}
//初始化;
function bulid()
{
var str = ""
+ "<div id=xMsg" + this.id + " "
+ "style='"
+ "z-index:" + this.zIndex + ";"
+ "width:" + this.width + ";"
+ "height:" + this.height + ";"
+ "left:" + this.left + ";"
+ "top:" + this.top + ";"
+ "background-color:" + normal + ";"
+ "color:" + normal + ";"
+ "font-size:10px;"
+ "font-family:Verdana;"
+ "position:absolute;"
+ "cursor:default;"
+ "border:2px solid " + normal + ";"
+ "' "
+ "onmousedown='getFocus(this)'>"
   + "<div "
   + "style='"
   + "background-color:" + normal + ";"
   + "width:" + (this.width-2*2) + ";"
   + "height:20;"
   + "color:white;"
   + "' "
   + "onmousedown='startDrag(this)' "
   + "onmouseup='stopDrag(this)' "
   + "onmousemove='drag(this)' "
   + ">"
   + "<span style='width:" + (this.width-2*12-4) + ";padding-left:3px;'>" + this.title + "</span>"
   + "<span style='width:12;border-width:0px;color:white;font-family:webdings;' onclick='min(this)'>0</span>"
   + "<span style='width:12;border-width:0px;color:white;font-family:webdings;' onclick='cls(this)'>r</span>"
   + "</div>"
   + "<div style='"
   + "width:100%;"
   + "height:" + (this.height-20-4) + ";"
   + "background-color:white;"
   + "line-height:14px;"
   + "word-break:break-all;"
   + "padding:3px;"
   + "'>" + this.message + "</div>"
+ "</div>"
+ "<div style='"
+ "width:" + this.width + ";"
+ "height:" + this.height + ";"
+ "top:" + this.top + ";"
+ "left:" + this.left + ";"
+ "z-index:" + (this.zIndex-1) + ";"
+ "position:absolute;"
+ "background-color:black;"
+ "filter:alpha(opacity=40);"
+ "'>?</div>";
//alert(str);
document.body.insertAdjacentHTML("beforeEnd",str);
}
//-->
</script>
<script language='JScript'>
<!--
function initialize()
{
var a = new xWin("1",160,200,200,200,"Message","xWin <br> A Cool Pop Div Window<br>Version:1.0<br>2002-8-13");
var b = new xWin("2",240,200,100,100,"Wildwind's Msgbox","Welcome to visited my personal website:<br><a href=http://www14.brinkster.com/wildcity target=_blank>http://wildcity.126.com</a><br>and u can also sign my guestbook at:<br><a href=http://www14.brinkster.com/wildcity/gbook target=_blank>http://wildcity.126.com/gbook</a><br><br>thx!!! =)...");
var c = new xWin("3",200,160,250,50,"Copyright","Copyright by <a href='mailto:wildwind_zz@21cn.com'>Wildwind</a>!");
}
window.onload = initialize;
//-->
</script>
</head>
<body onselectstart='return false' oncontextmenu='return false'>
</body>
</html>

本文出自:钱大宝的博客地,地址:http://www.qiandabao.com/cxrs/247.html,转载须注明!

« asp.net弹出遮蔽层的方法 gridview数据绑定格式设置实例 »

目录
相关文章
|
1月前
|
自然语言处理 JavaScript 前端开发
探索JavaScript中的闭包:理解其原理与实际应用
探索JavaScript中的闭包:理解其原理与实际应用
19 0
|
3月前
|
JavaScript
Vue3 + Js 指定位置进行拖动
Vue3 + Js 指定位置进行拖动
|
3月前
|
前端开发 JavaScript 算法
【面试题】 JavaScript 中的深浅拷贝: 原理与实现
【面试题】 JavaScript 中的深浅拷贝: 原理与实现
|
3月前
|
JavaScript 数据可视化
基于fabric.js的图片编辑器, 画布背景实现原理
基于vue3 + fabric.js + vite + element-plus + typescript等技术,画布背景原理分析
基于fabric.js的图片编辑器, 画布背景实现原理
|
3月前
|
Web App开发 JavaScript 前端开发
Node.js 的事件循环原理、工作流程
Node.js 的事件循环原理、工作流程
52 0
|
1月前
|
JavaScript
JS数组增删方法的原理,使用原型定义
JS数组增删方法的原理,使用原型定义
|
2天前
|
前端开发 JavaScript 编译器
深入解析JavaScript中的异步编程:Promises与async/await的使用与原理
【4月更文挑战第22天】本文深入解析JavaScript异步编程,重点讨论Promises和async/await。Promises用于管理异步操作,有pending、fulfilled和rejected三种状态。通过.then()和.catch()处理结果,但可能导致回调地狱。async/await是ES2017的语法糖,使异步编程更直观,类似同步代码,通过事件循环和微任务队列实现。两者各有优势,适用于不同场景,能有效提升代码可读性和维护性。
|
1月前
|
JavaScript
JS中call()、apply()、bind()改变this指向的原理
JS中call()、apply()、bind()改变this指向的原理
|
1月前
|
JavaScript 前端开发 API
Vue.js 深度解析:nextTick 原理与应用
Vue.js 深度解析:nextTick 原理与应用
|
2月前
|
缓存 JavaScript 前端开发
深入理解Vue.js 3中的响应式原理与使用技巧
【2月更文挑战第1天】Vue.js 3作为一款流行的前端框架,其核心特性之一是响应式数据绑定。本文将深入探讨Vue.js 3中的响应式原理,包括Reactivity API的设计思路和实现原理,并结合实际案例介绍在项目中如何有效地利用Vue.js 3的响应式特性。通过本文的学习,读者将更加全面地理解Vue.js 3的内部工作原理,提升在前端开发中的实践能力。
78 2