码迷,mamicode.com
首页 > 其他好文 > 详细

div的拖拽练习

时间:2015-12-14 16:10:31      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

   学完js基础后,一直在找一些题目在练习。下面是div模块的拖拽例子,废话不多说,直接上代码:

<html>

<head>

<title>拖拽</title>
<style type="text/css">
#box {

width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>

</head>
<body>
<div id="box"></div>
<script type="text/javascript">
window.onload = drag;

function drag(){
var boxElement = document.getElementById("box");
boxElement.onmousedown = function(){
event = event || window.event;
down(event, box);
}
}

//鼠标按下时,获取光标相对于div的位置。
function down(e, el){
disX = event.clientX - el.offsetLeft;
disY = event.clientY - el.offsetTop;
el.onmousemove = function(){
event = event || window.event;
move(event, disX, disY);
}

//取消鼠标事件的绑定
el.onmouseup = function(){
el.onmousemove = null;
el.onmouseup = null;
}

}

//div根据光标的位置进行移动
function move(event, posX, posY){
var boxElement = document.getElementById("box");
var l = event.clientX - posX;
var t = event.clientY - posY;
var winW = document.documentElement.clientWidth || document.body.clientWidth;
var winH = document.documentElement.clientHeight || document.body.clientHeight;
console.log(winW + " "+ winH);
var maxW = winW - boxElement.offsetWidth;
var maxH = winH - boxElement.offsetHeight;
if(l < 0){
l = 0;
}else if(l > maxW){
l = maxW;
}
if(t < 0){
t = 0;
}else if(t > maxH){
t = maxH;
}

boxElement.style.left = l + ‘px‘;
boxElement.style.top = t + ‘px‘;
}
</script>
</body>
</html>

div的拖拽练习

标签:

原文地址:http://www.cnblogs.com/nash-test/p/5045386.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!