您的位置:首页 > Web前端 > JavaScript

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

2008-12-08 18:24 459 查看
共享一个简单的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").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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐