一个超简单的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页面布局拖拽效果代码


有用  |  无用

猜你喜欢