欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

JavaScript 拖放效果_html/css_WEB-ITnose

程序员文章站 2023-12-26 19:55:57
...
拖放效果,也叫拖拽、拖动。一个简单的拖放效果

拖动div

【程序说明】

首先初始化函数,对拖放对象添加mousedown监听事件

 initialize:function(drag){        this.Drag = $$(drag);//拖放对象        this._x = this._y = 0;//记录鼠标相对于拖放对象的位置        this._fM = BindAsEventListener(this, this.Move); //绑定拖动时执行的函数        this._fS = Bind(this, this.Stop); //绑定拖动结束执行的函数        this.Drag.style.position = "absolute";        EventUtil.addEventHandler(this.Drag, "mousedown", BindAsEventListener(this, this.Start));           //监听拖动对象mousedown事件 }

之后在Start方法添加mousemove和mouseup事件,分别监听拖放对象的位置和取消监听事件

             Start:function(oEvent){                 //记录mousedown触发时鼠标相对于拖放对象的位置                 this._x = oEvent.clientX - this.Drag.offsetLeft;                 this._y = oEvent.clientY - this.Drag.offsetTop;                 //监听mousemove 和 mouseup事件                 EventUtil.addEventHandler(document, "mousemove", this._fM);                 EventUtil.addEventHandler(document, "mouseup", this._fS);             }

完整拖放程序:

         /**          *拖放程序          */         var simpleDrag = Class.create();         simpleDrag.prototype = {             //初始化对象             initialize:function(drag){                 this.Drag = $$(drag);//拖放对象                 this._x = this._y = 0;//记录鼠标相对于拖放对象的位置                 this._fM = BindAsEventListener(this, this.Move); //绑定拖动时执行的函数                this._fS = Bind(this, this.Stop); //绑定拖动结束执行的函数                this.Drag.style.position = "absolute";                EventUtil.addEventHandler(this.Drag, "mousedown", BindAsEventListener(this, this.Start));                 //监听拖动对象mousedown事件             },             //准备拖动                 Start:function(oEvent){                 //记录mousedown触发时鼠标相对于拖放对象的位置                 this._x = oEvent.clientX - this.Drag.offsetLeft;                this._y = oEvent.clientY - this.Drag.offsetTop;                //监听mousemove 和 mouseup事件                EventUtil.addEventHandler(document, "mousemove", this._fM);                EventUtil.addEventHandler(document, "mouseup", this._fS);             },                 //拖动             Move:function(oEvent){                 this.Drag.style.left = oEvent.clientX - this._x + "px";                this.Drag.style.top = oEvent.clientY - this._y + "px";             },             //停止拖动             Stop:function(){                EventUtil.removeEventHandler(document, "mousemove", this._fM);                EventUtil.removeEventHandler(document, "mouseup", this._fS);             },         };        //初始化拖动         new simpleDrag('drag');

完整DEMO:

JavaScript拖放效果
拖动div

上一篇:

下一篇: