欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jquery实现拖动效果(代码分享)

程序员文章站 2023-02-23 12:55:43
话不多说,请看代码:

话不多说,请看代码:

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>document</title>
</head>
<body>
 <style type="text/css">
 .page{text-align:left;}
 .dragdiv{border:1px solid #ddd; padding:10px; width:300px; margin:0 auto; border-radius:4px; box-shadow:0 1px 2px #fefefe; position: fixed;}
 </style>
 <div class="dragdiv" id="drag">
 <div class="drag-head">自己动手试试</div>
 <div class="drag-body">
 点击鼠标拖拖看
 </div>
 </div>
</body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
 var _drag = {};
 _drag.top = 0; //拖动过的位置距离上边
 _drag.left = 0; //拖动过的位置距离左边
 _drag.maxleft; //距离左边最大的距离
 _drag.maxtop; //距离上边最大的距离
 _drag.dragging = false; //是否拖动标志
 //拖动函数
 function binddrag(el){ 
 var winwidth = $(window).width(), winheight =$(window).height(),objwidth = $(el).outerwidth(), objheight = $(el).outerheight();
 _drag.maxleft = winwidth - objwidth, _drag.maxtop = winheight - objheight;
 var els = el.style,x=0,y=0;
 var objtop = $(el).offset().top, objleft = $(el).offset().left;
 $(el).mousedown(function(e){ 
 _drag.dragging = true;
 _drag.isdragged = true;
 x = e.clientx - el.offsetleft; 
 y = e.clienty - el.offsettop; 
 el.setcapture && el.setcapture(); 
 $(document).bind('mousemove',mousemove).bind('mouseup',mouseup);
 return false;
 }); 
 function mousemove(e){ 
 e = e || window.event;
 if(_drag.dragging){
 _drag.top = e.clienty - y; 
 _drag.left = e.clientx - x;
 _drag.top = _drag.top > _drag.maxtop ? _drag.maxtop : _drag.top;
 _drag.left = _drag.left > _drag.maxleft ? _drag.maxleft : _drag.left;
 _drag.top = _drag.top < 0 ? 0 : _drag.top;
 _drag.left = _drag.left <0 ? 0 : _drag.left;
 els.top = _drag.top + 'px'; 
 els.left = _drag.left+ 'px';
 return false;
 }
 } 
 function mouseup(e){ 
 _drag.dragging = false; 
 el.releasecapture && el.releasecapture(); 
 e.cancelbubble = true;
 $(document).unbind('mousemove',mousemove).unbind('mouseup',mouseup); 
 }
 $(window).resize(function(){
 var winwidth = $(window).width(),
 winheight = $(window).height(),
 el = $(el),
 elwidth = el.outerwidth(),
 elheight = el.outerheight(),
 elleft = parsefloat(el.css('left')),
 eltop = parsefloat(el.css('top'));
 _drag.maxleft = winwidth - elwidth;
 _drag.maxtop = winheight - elheight;
 _drag.top = _drag.maxtop < eltop ? _drag.maxtop : eltop;
 _drag.left = _drag.maxleft < elleft ? _drag.maxleft : elleft;
 el.css({
 top:_drag.top,
 left:_drag.left
 })
 })
 } 
 binddrag(document.getelementbyid('drag'));
</script>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!