• 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属性,当点击元素的时候,会检查该元素是否有这个属性,如果有,则进行拖拽。

  • 相关阅读:
    【BOOST C++ 13 并行编程】(3) 线程本地存储
    聊聊接口设计的36个小技巧
    Entity Developer数据库应用程序的开发
    Nginx 文件解析漏洞复现
    【669. 修剪二叉搜索树】
    Page Cache难以回收产生之直接内存回收引起 load 飙高或者业务时延抖动
    高效率开发Web安全扫描器之路(一)
    c++primer
    HR的职业规划
    python functools.wraps保留被装饰函数属性
  • 原文地址:https://blog.csdn.net/qq_58192905/article/details/133545890