学完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>