寫在前面厕宗,初學者,共同進步 奠货,個人筆記分享
01
拖拽.gif
拖拽
網(wǎng)頁中經(jīng)常需要div的拖動介褥,這里寫的封裝的一個函數(shù)是無限制的拖拽,可以在子類中添加各種限制條件仇味,完成拖拽呻顽。
02
- 面向對象的方法,構造函數(shù)里保存屬性丹墨,方法使用**函數(shù)名.prototype.方法名
** - ** disX與disY分別是鼠標與div**的橫向和縱向距離
- var _this = this; 解決了在后面的事件添加中廊遍,this的變化導致的錯誤
- 添加鼠標移動函數(shù)
/**
* @constructor
* @param {String} id = id為盒子div的id
* @description 拖拽
* @example
* var myDrag = new Drag('id');
*/
function Drag(id) {
this.disX = 0;
this.disY = 0;
var _this = this;
this.oDiv = document.getElementById(id);
//鼠標按下事件
this.oDiv.onmousedown = function() {
_this.Down();
//阻止默認事件
return false;
};
}
03方法
鼠標按下
- 先記錄鼠標按下的位置與div之間的距離
- 在鼠標按下函數(shù)中綁定鼠標移動和抬起事件
- setCapture函數(shù)功能:一旦窗口捕獲了鼠標,所有鼠標輸入都針對該窗口贩挣,無論光標是否在窗口的邊界內(nèi)喉前。同一時刻只能有一個窗口捕獲鼠標没酣。如果鼠標光標在另一個線程創(chuàng)建的窗口上,只有當鼠標鍵按下時系統(tǒng)才將鼠標輸入指向指定的窗口卵迂。 簡單來說裕便,這里添加的意義就是在div上的事件,我們拖動div時见咒,不會選中頁面的其他內(nèi)容偿衰。
//鼠標按下函數(shù)
Drag.prototype.Down = function(ev) {
var _this = this;
var oEvent = ev || event;
//在鼠標按下的時候記錄鼠標與div之間的橫向縱向距離
this.disX = oEvent.clientX - _this.oDiv.offsetLeft;
this.disY = oEvent.clientY - _this.oDiv.offsetTop;
//事件綁定 解決拖動文字被選中的問題
if (this.oDiv.setCapture) {
//IE
this.oDiv.onmousemove =function(){
_this.fnMove(ev);
};
this.oDiv.onmouseup = function(){
_this.fnUp(this);
};
this.oDiv.setCapture();
} else{
document.onmousemove = function(ev) {
_this.fnMove(ev);
};
document.onmouseup = function() {
_this.fnUp(this);
};
}
}
鼠標移動與抬起
- 動態(tài)獲取鼠標的位置,根據(jù)鼠標按下時存儲的距離改览,計算div的位置下翎,實時更新
- 鼠標抬起時釋放事件
//鼠標移動時根據(jù)鼠標的位置計算div的位置并實時更新位置
Drag.prototype.fnMove = function(ev) {
var oEvent = ev || event;
var left = oEvent.clientX - this.disX;
var top = oEvent.clientY - this.disY;
this.oDiv.style.left = left + 'px';
this.oDiv.style.top = top + 'px';
}
//鼠標抬起來的時候釋放鼠標移動以及抬起事件
Drag.prototype.fnUp = function(oAttr) {
oAttr.onmousemove = null;
oAttr.onmouseup = null;
//需要釋放捕獲的事件
if (oAttr.releaseCapture) {
oAttr.releaseCapture();
}
}
04 使用
new Drag( );
- new一個實例
- 可以重寫父類的方法
05 封裝函數(shù)源碼與小例子
js文件可直接引用
Drag.js 框架下載
運用的例子