• JavaScript事件之拖拽事件(详解)


      在网页开发的过程中我们经常会接触到拖拽事件,虽然每个网页和每个网页的拖拽的效果大相径庭,但是从根本来讲,代码是几乎一模一样的。
      简而言之,拖拽效果就是鼠标按下,被拖拽的元素随着鼠标而移动,鼠标松开,被拖拽的元素停止拖拽。所以,我们需要使用onmousedownonmouseup两个事件。
      在鼠标按下的时候,我们需要先获取鼠标当前点击事件距离元素左侧和顶端的距离(needX,needY)。

    			var needX = event.clientX - this.offsetLeft;
    			var needY = event.clientY - this.offsetTop;
    
    • 1
    • 2

      但是当我们拖拽元素的时候,我们需要让元素的lefttop两个属性随着改变,元素的left属性即鼠标点击事件的位置减去鼠标事件距离元素左端的距离。即:

    			document.onmousemove = function(){
    				div.style.left = event.clientX - needX + 'px';
    				div.style.top  = event.clientY - needY + 'px';
    			};
    
    • 1
    • 2
    • 3
    • 4

      同时,当我们鼠标抬起的时候,我们需要清空onmousedownonmouseup两个事件,防止对之后的操作进行干扰。

    			document.onmouseup = function(){
    				this.onmousemove = this.onmouseup = null;
    			};
    
    • 1
    • 2
    • 3

    所以,综上,拖拽效果合代码如下

    div.onmousedown = function(){
    			var needX = event.clientX - this.offsetLeft;
    			var needY = event.clientY - this.offsetTop;
    			document.onmousemove = function(){
    				div.style.left = event.clientX - needX + 'px';
    				div.style.top  = event.clientY - needY + 'px';
    			};
    			document.onmouseup = function(){
    				this.onmousemove = this.onmouseup = null;
    			};
    			return false;
    		};
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    优化版本:

    document.documentElement.onmousedown = function(){
    			if(event.srcElement.getAttribute('drag') == 'drag'){
    				var _this = event.srcElement||event.target;
    				var needX = event.clientX - _this.offsetLeft;
    				var needY = event.clientY - _this.offsetTop;
    				document.onmousemove = function(){
    					_this.style.left = event.clientX - needX + 'px';
    					_this.style.top  = event.clientY - needY + 'px';
    				};
    				document.onmouseup = function(){
    					this.onmousemove = this.onmouseup = null;
    				};
    				return false;
    			};
    		};
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    该版本是给要拖拽的元素添加了一个drag属性,当点击元素的时候,会检查该元素是否有这个属性,如果有,则进行拖拽。

  • 相关阅读:
    工业无线路由器助力打造高速路多功能测速杆
    css 星星闪烁加载框
    Mybatis03-ResultMap及分页
    时间序列分析1--生成和导出时间序列数据
    Kaldi语音识别技术(四) ----- 完成G.fst的生成
    【WMWare 克隆CentOS虚拟机 】解决克隆后 ip 冲突 & 主机名重复问题
    MVP 聚技站|.NET C# 系列(二):创建并运行简单的 C# 控制台应用程序
    现在的国产深度deepin操作系统不赖,推荐试用
    CSS复习之选择器
    基于java+springboot+vue实现的美食信息推荐系统(文末源码+Lw)23-170
  • 原文地址:https://blog.csdn.net/qq_58192905/article/details/133545890