拖拽效果

<!DOCTYPE html>
<!--
作者:1243860037@qq.com
时间:2017-10-26
描述:
实现鼠标拖拽元素效果
分析:发生以下事件
1、按下onmousedown 选中元素
2、拖动onmousemove 拖动元素
3、释放onmouseup 抬起释放元素
注意关系23事件要在1事件里面执行,因为他们的前提都是鼠标按下后的
-->
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<style>
div{width: 50px;height: 50px;background: red;position: absolute;}
</style>
<script>
window.onload=function()
{
var odiv=document.getElementById("div1");
odiv.onmousedown=function() //按下
{ //拖动
document.onmousemove=function(e) //不能用odiv。onmousemove
{
var e=e||event;
odiv.style.left=e.clientX+'px';
odiv.style.top=e.clientY+'px';
}
document.onmouseup=function() //释放
{
document.onmousemove=document.onmouseup=null;
}
/*下一行的代码是为了删除浏览器的默认行为。当有文字被选中时,
如Ctrl+a全选后再拖动时会有bug,就是文字和div块一起移动,释放时div块
还在动,所以要删除浏览器的默认行为*/
return false;
}
}
</script>
</head>
<body>
一段测试文字
<div id='div1'></div>
</body>
</html>

posted on 2017-10-26 14:17  xiaoxiaoyao61  阅读(121)  评论(0编辑  收藏  举报

导航