代码改变世界

js 拖动层示例[转]

2011-07-06 22:38  ☆冷枫☆  阅读(256)  评论(0编辑  收藏  举报
共享一个简单的JS拖动层效果,支持ie,ff,opera,safari;

ie有专门的拖动方法:dragstart,drag,dragend分别是开始拖动,拖动,结束拖动。但是其他浏览器(dom类,例如ff)不支持这些拖动方法。所以只能用鼠标事件模拟拖动层效果。

实现原理:

我们知道用户使用拖动效果,需要完成一下事件

1.在某个区域按下鼠标左键,

2.按住鼠标左键不放,拖动鼠标;

3.拖到合适的位置后,放开鼠标左键。

这3步用JS的事件来描述的话就是:

用户在可拖动区域onmousedown,并在onmousedown的情况下触发onmousemove事件,当onmouseup的时候移除onmousemove事件。

看代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js拖动层示例</title>
</head>

<body>
<div id="f" style="position: absolute; width: 200px; height: 150px; background-color: #ccc; top: 150px; left: 200px; z-index: 101; border: solid 1px blue;">
  
<div id="title" style="background-color: Blue; cursor: move; height: 20px; color: #fff;font-size: 13px; padding-top: 5px; padding-left: 10px;"> 拖动层 </div>
  
</div>
<script type="text/javascript">
var posX;
var posY;  
fdiv 
= document.getElementById("f");  
document.getElementById(
"title").onmousedown=function(e)
{
  
if(!e) e = window.event; //如果是IE
  posX = e.clientX - parseInt(fdiv.style.left);
  posY 
= e.clientY - parseInt(fdiv.style.top);
  document.onmousemove 
= mousemove;  
}
document.onmouseup 
= function()
{
  document.onmousemove 
= null;
}
function mousemove(ev)
{
  
if(ev==null) ev = window.event;//如果是IE
  fdiv.style.left = (ev.clientX - posX) + "px";
  fdiv.style.top 
= (ev.clientY - posY) + "px";
}
</script>

</body>
</html>