拖拽的关键在于事件源及坐标位
网页中的基本拖拽:
1.设定是否激活拖拽的标识flag;
2.当拖拽点按下时,在window范围内的移动;
3.拖拽区域不能超过窗口,加判断
HTML:
body>div
CSS代码:
<style> div{ width:100px; height:100px; background: lightgrey; position: absolute; top:0; left:0; } </style>
JQ代码:
<script> $(function(){ //是否激活拖拽的标识 var flag = false; var w1 = $(‘div‘).width(); var h1 = $(‘div‘).height(); var w2 = $(window).width(); var h2 = $(window).height(); $(‘div‘).mousedown(function(){ flag = true; $(window).mousemove(function(event) { if(flag == true){ var mx = event.pageX; var my = event.pageY; var x = mx-20; var y = my-20; if(x<0){ x=0; } if(y<0){ y=0; } if(x>w2-w1){ x = w2-w1; } if(y>h2-h1){ y=h2-h1; } $(‘div‘).css({left:x,top:y}); } }); }) $(window).mouseup(function(event) { /* Act on the event */ flag=false; }); }) </script>
指定在有效范围内的拖拽:
1.拖拽的三个事件,拖拽点鼠标按下,移动范围内的鼠标移动,窗口范围内鼠标松开
2.三个距离:1-父盒子离窗口边框距离;2。拖拽点坐标;3.前两者之差即为拖拽点在父盒子中的大致位置
3.注意:拖拽点不能超出盒子,因此需加判断
HTML:
body>div>span
CSS:
div{ width: 1000px; height: 500px; background: #ccc; border:1px solid #000; margin:100px auto; position: relative; } span{ width:100px; height: 100px; background: green; border:1px solid #000; position: absolute; left: 0; top: 0; } </style>
JQ:
$(function(){ var divX = $(‘div‘).offset().left; var divY = $(‘div‘).offset().top; var w1 = $(‘span‘).width(); var h1 = $(‘span‘).height(); var w2 = $(‘div‘).width(); var h2 = $(‘div‘).height(); var flag = false; //拖拽激活标识 $(‘span‘).mousedown(function(event) { flag = true; $(‘div‘).mousemove(function(event) { /* Act on the event */ var mx = event.pageX; var my = event.pageY; if(flag == true){ var x = mx - divX - 50; //拖拽点在span中间 var y = my - divY - 50; //移动范围在div中 if(x <0){ x=0; } if(y<0){ y=0; } if(x>w2-w1){ x=w2-w1; } if(y>h2-h1){ y=h2-h1; } $(‘span‘).css({left:x,top:y}); } }); }); $(window).mouseup(function(event) { /* Act on the event */ flag = false; }); })
时间: 2024-10-06 10:54:37