您好,登錄后才能下訂單哦!
本篇內容介紹了“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。