基于jQuery拖拽事件的封裝
更新時間:2020年11月29日 09:50:19 作者:Spicy boy
這篇文章主要為大家詳細(xì)介紹了基于jQuery拖拽事件的封裝,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了基于jQuery封裝的拖拽事件,供大家參考,具體內(nèi)容如下
HTML代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="jquery-3.4.1.min.js"></script> <script src="Drag.js"></script> <title>Document</title> <style> *{ padding: 0; margin: 0; } .box{ height: 200px; width: 200px; background-color: red; position: absolute; /* 讓文字無法被選中 */ user-select:none; } </style> </head> <body> <div class="box"></div>box</div> <script> $('.box').Drag();//直接調(diào)用Drag()方法就可以了 </script> </body> </html>
封裝的jQuery拖拽事件:
;(function($) { $.fn.extend({ Drag(){ //把this存起來,始終指向操作的元素 _this = this; this.on('mousedown',function (e) { //盒子距離document的距離 var positionDiv = $(this).offset(); //鼠標(biāo)點擊box距離box左邊的距離 var distenceX = e.pageX - positionDiv.left; //鼠標(biāo)點擊box距離box上邊的距離 var distenceY = e.pageY - positionDiv.top; $(document).mousemove(function(e) { //盒子的x軸 var x = e.pageX - distenceX; //盒子的y軸 var y = e.pageY - distenceY; //如果盒子的x軸小于了0就讓他等于0(盒子的左邊界值) if (x < 0) { x = 0; } //盒子右邊界值 if(x > $(document).width() - _this.outerWidth()){ x = $(document).width() - _this.outerWidth(); } //盒子的上邊界值 if (y < 0) { y = 0; } //盒子的下邊界值 if(y > $(document).height() - _this.outerHeight()){ y = $(document).height() - _this.outerHeight(); } //給盒子的上下邊距賦值 $(_this).css({ 'left': x, 'top': y }); }); //在頁面中當(dāng)鼠標(biāo)抬起的時候,就關(guān)閉盒子移動事件 $(document).mouseup(function() { $(document).off('mousemove'); }); }) //把this返回回去繼續(xù)使用jqurey的鏈?zhǔn)秸{(diào)用 return this } }) })(jQuery)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
JavaScript的jQuery庫中function的存在和參數(shù)問題
這篇文章主要介紹了JavaScript的jQuery庫中function的存在和參數(shù)問題,包括function的參數(shù)傳遞和檢測一個jQuery方法是否存在等,需要的朋友可以參考下2015-08-08jQuery結(jié)合CSS制作漂亮的select下拉菜單
對于我來說,標(biāo)準(zhǔn)的HTML元素(Select)已經(jīng)讓我感到討厭。它不能夠正常的在IE瀏覽器上顯示。還有一點就是他并不僅僅包含簡單的文本。本實例將完全摒棄select元素,通過JQuery和CSS來構(gòu)建DropDown元素。2015-05-05