<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>拖拽效果限制范围</title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
body{
padding:50px;
}
#box{
width:350px;
height:250px;
background:red;
overflow:hidden;
position:relative;
}
#drag{
width:50px;
height:50px;
background:green;
position:absolute;
}
</style>
<script type="text/javascript">
window.onload=function(){
var obox=document.getElementById("box");
var odrag=document.getElementById("drag");
var isDrag=false;
var x,y;
odrag.onmousedown=down;
document.onmousemove=move;
document.onmouseup=up;
function down(ev){
var ev=window.event||ev;
x=ev.clientX-this.offsetLeft;
y=ev.clientY-this.offsetTop;
this.style.cursor="move";
isDrag=true;
}
function move(ev){
if(isDrag){
var ev=window.event||ev;
odrag.style.left=(ev.clientX-x)+"px";
odrag.style.top=(ev.clientY-x)+"px";
if(parseInt(odrag.style.left)<0){
odrag.style.left=0;
}
if(parseInt(odrag.style.top)<0){
odrag.style.top=0;
}
if(parseInt(odrag.style.left)>obox.clientWidth-odrag.clientWidth){
odrag.style.left=(obox.clientWidth-odrag.clientWidth)+"px";
}
if(parseInt(odrag.style.top)>obox.clientHeight-odrag.clientHeight){
odrag.style.top=(obox.clientHeight-odrag.clientHeight)+"px";
}
}
}
function up(){
isDrag=false;
odrag.style.cursor="pointer";
}
}
</script>
</head>
<body>
<div id="box">
<div id="drag"></div>
</div>
</body>
</html>
javascript实现拖拽div效果
最新推荐文章于 2024-04-19 15:39:51 发布