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

  • 相关阅读:
    计算机毕业设计Java中华美食文化网站(源码+系统+mysql数据库+Lw文档)
    2022-08-31 第五组 张明敏 第五组
    激光雷达:自动驾驶的眼睛
    EntityDAC添加了对Apple iOS 15的支持
    [RoarCTF 2019]Easy Calc
    2023年,新手如何玩赚互联网项目?
    移动通信覆盖自愈的研究与实现
    【Maven教程】(四)坐标与依赖:坐标概念,依赖配置、范围、传递性和最佳实践 ~
    Compose中Canvas绘制
    C++之修改结构体成员字节对齐(二百一十三)
  • 原文地址:https://blog.csdn.net/qq_58192905/article/details/133545890