首页 > web前端 > js教程 > 正文

jquery实现拖动效果

高洛峰
发布: 2017-02-08 17:17:09
原创
997 人浏览过

话不多说,请看代码:

<!DOCTYPE html>
<html>
<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 id="drag">
 <div>自己动手试试</div>
 <div>
 点击鼠标拖拖看
 </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(&#39;mousemove&#39;,mouseMove).bind(&#39;mouseup&#39;,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 + &#39;px&#39;; 
 els.left = _drag.left+ &#39;px&#39;;
 return false;
 }
 } 
 function mouseUp(e){ 
 _drag.dragging = false; 
 el.releaseCapture && el.releaseCapture(); 
 e.cancelBubble = true;
 $(document).unbind(&#39;mousemove&#39;,mouseMove).unbind(&#39;mouseup&#39;,mouseUp); 
 }
 $(window).resize(function(){
 var winWidth = $(window).width(),
 winHeight = $(window).height(),
 el = $(el),
 elWidth = el.outerWidth(),
 elHeight = el.outerHeight(),
 elLeft = parseFloat(el.css(&#39;left&#39;)),
 elTop = parseFloat(el.css(&#39;top&#39;));
 _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(&#39;drag&#39;));
</script>
</html>
登录后复制

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

更多jquery实现拖动效果相关文章请关注PHP中文网!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板