本篇内容介绍了“jquery怎么实现拖动效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
代码如下:
<!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>
“jquery怎么实现拖动效果”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。