JS拖动层(支持ie,ff,opera,safari)

共享一个简单的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>无标题文档</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").οnmοusedοwn=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>

转载于:https://www.cnblogs.com/guowei1027/archive/2009/12/21/1628539.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值