一个超简单的JS拖拽实现代码(兼容IE,Firefox)
作者:bea
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>runcode</title> <meta http-equiv="Cont
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>runcode</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta name="Author" content="Sheneyan" />
<script type="text/javascript">
/**
*取得元素的真实css属性
*@param {Object} d 元素
*@param {String} a 元素的css属性名
*@version 0.2
*/
function gs(d,a){
if (d.currentStyle){
var curVal=d.currentStyle[a]
}else{
var curVal=document.defaultView.getComputedStyle(d, null)[a]
}
return curVal;
}
/**
* 取得鼠标坐标
* @return Position
*/
function getMouseLocation(e){
if(!document.all){
mouseX = e.pageX;
mouseY = e.pageY;
}
else{
mouseX = event.x + document.body.scrollLeft;
mouseY = event.y + document.body.scrollTop;
}
return {x:mouseX,y:mouseY};
}
/**
* 拖动对象
* @param {DOM Object} DOM对象
*/
function drag(e,obj){
var p1 = getMouseLocation(e);
var startRight = null;
var startTop = null;
var startLeft = null;
var startBottom = null;
var l = gs(obj,"left");
var r = gs(obj,"right");
var t = gs(obj,"top");
var b = gs(obj,"bottom");
if(!l)
startRight = parseInt(r);
else
startLeft = parseInt(l);
if(!t)
startBottom = parseInt(b);
else
startTop = parseInt(t);
if(obj.setCapture)
obj.setCapture();
else if (window.captureEvents)
window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
document.onmousemove = function(e){
var p2 = getMouseLocation(e);
var xMove = p2.x-p1.x;
var yMove = p2.y-p1.y;
if(!l)
obj.style.right = (startRight - xMove)+"px";
else
obj.style.left = (startLeft + xMove)+"px";
if(!t)
obj.style.bottom = (startBottom - yMove)+"px";
else
obj.style.top = (startTop + yMove)+"px";
}
document.onmouseup = function(){
if(obj.releaseCapture)
obj.releaseCapture();
else if (window.captureEvents)
window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
document.onmouseup = null;
document.onmousemove = null;
}
}
</script>
<style type="text/css">
div#test{border:solid 1px blue;background:red;position:absolute;left:100px;top:200px;width:200px;height:200px;cursor:pointer;}
</style>
</head>
<body>
<div id="test" onmousedown="drag(event,this)">拖我拖我拖我拖我拖我拖我拖我<div>
</body>
</html>
[Ctrl+A 全选 注:
如需引入外部Js需刷新才能执行]
javascript支持firefox,ie7页面布局拖拽效果代码
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- jQuery asp.net 用json格式返回自定义对象
- FileUpload 控件 禁止手动输入或粘贴的实现代码
- js 小贴士一星期合集
- javascript 函数使用说明
- js下获取div中的数据的原理分析
- Exjs 入门篇
- javascript window.opener的用法分析
- JS的反射问题
- Extjs在exlipse中设置自动提示的方法
- javascript setTimeout()传递函数参数(包括传递对象参数)
- javascript在事件监听方面的兼容性小结
- javascript 程序库的比较(一)之DOM功能
- JS 文件大小判断的实现代码
- 查看QQ是否在线状态的网页代码
- 用jQuery简化Ajax开发实现方法
- 基于jquery的一个简单的脚本验证插件
- js获取单元格自定义属性值的代码(IE/Firefox)
- js+json用表格实现简单网站左侧导航
- offsetParent 算法分析