js完美拖拽效果,兼容各大浏览器!
setCapture:事件捕获,IE下兼容;在IE下,事件对象为拖拽元素本身(div),标准下事件对象为document,注意在IE下事件捕获之后要释放事件捕获!
<!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=gb2312" />
<title>完美拖拽</title>
<style type="text/css">
#div1{ width:150px; height:90px; background:#ccc; position:absolute; left:0; top:0; text-align:center;}
</style>
<script type="text/javascript">
window.οnlοad=function()
{
var div1=document.getElementById('div1')
var li=div1.getElementsByTagName('li')
div1.οnmοusedοwn=function(ev) //拖拽事件必须在鼠标按下后执行
{
var ev = ev || window.event
var left=ev.clientX-div1.offsetLeft
var top=ev.clientY-div1.offsetTop
if(div1.setCapture)
{
//IE下
div1.οnmοusemοve=mouseMove
div1.οnmοuseup=mouseUp
div1.setCapture()
}
else
{
//chrome/FF下
document.οnmοusemοve=mouseMove
document.οnmοuseup=mouseUp
}
function mouseMove(ev)
{
var ev = ev || window.event
var l=ev.clientX-left
var t=ev.clientY-top
div1.style.left=l+'px'
div1.style.top=t+'px'
}
function mouseUp()
{
this.οnmοusemοve=null
this.οnmοuseup=null
if(div1.setCapture)
{
div1.releaseCapture()
}
}
return false;//阻止火狐和chrome等的BUG
}
}
</script>
</head>
<body>
兼容兼容兼容兼容兼容兼容兼容兼容
兼容兼容兼容兼容
兼容兼容兼容兼容兼容兼容兼容兼容
<div id="div1">
拖拽对象
</div>
兼容兼容兼容兼容兼容兼容兼容兼容
</body>
</html>