zoukankan      html  css  js  c++  java
  • JavaScript鼠标拖拽特效及相关问题总结

    #div1{200px;height:200px;background:red;position:absolute;}
    #div2{200px;height:200px;background:green;position:absolute;left:300px;}
    
    <div id="div1">原来的  普通拖拽</div>
    <div id="div2">继承的 限制范围拖拽</div>
    
    window.onload=function()
    {
        new Drag('div1');
        new LimitDrag('div2');
    };
    
    function Drag(id)
    {
        this.disX=0;
        this.disY=0;
        var _this=this;
        this.oDiv=document.getElementById(id);
        
        this.oDiv.onmousedown=function(ev)
        {
            _this.fnDown(ev);
            return false;
        };
    };
    
    Drag.prototype.fnDown=function(ev)
    {
        var _this=this;
        var oEvent=ev||event;
        
        this.disX=oEvent.clientX-this.oDiv.offsetLeft;
        this.disY=oEvent.clientY-this.oDiv.offsetTop;
        
        document.onmousemove=function(ev)
        {
            _this.fnMove(ev);
        };
        
        document.onmouseup=function()
        {
            _this.fnUp();
        };
    };
    
    Drag.prototype.fnMove=function(ev)
    {
        var oEvent=ev||event;
        this.oDiv.style.left=oEvent.clientX-this.disX+'px';
        this.oDiv.style.top=oEvent.clientY-this.disY+'px';
    };
    
    Drag.prototype.fnUp=function()
    {
        document.onmousemove=null;
        document.onmouseup=null;    
    };
    
    /*继承*/
    function LimitDrag(id)
    {
        Drag.call(this,id);
    };
    
    for(var i in Drag.prototype)
    {
        LimitDrag.prototype[i]=Drag.prototype[i];
    };
    
    LimitDrag.prototype.fnMove=function (ev)
    {
        var oEvent=ev||event;
        var l=oEvent.clientX-this.disX;
        var t=oEvent.clientY-this.disY;
        
        if(l<0)
        {
            l=0;
        }
        else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth)
        {
            l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
        }
        
        this.oDiv.style.left=l+'px';
        this.oDiv.style.top=t+'px';
    };
    

    鼠标拖拽效果最容易出现几个问题:

    1、元素脱离鼠标,原因是“鼠标不离开元素基本不可能,这跟浏览器解析速度有关,浏览器解析速度又跟CPU有关”,所以元素脱离鼠标是必然的,解决办法就是采用事件委托,把事件委托到document上,而不是需要拖拽的元素上,事件本身是会冒泡的,会触发委托在document上的事件

    2、元素的left和top值不能简单的设置为event.clientX或者是event.clientY,必须考虑鼠标在元素上的位置,否则元素很容易脱离鼠标

  • 相关阅读:
    no module name cx_oracle 的解决方法
    开通博客
    普通用户启动Hadoop格式化namenode出现无法创建目录的问题
    改写文件权限时出现问题___2
    suse添加普通用户赋予root所有权限时出现问题___1
    suse系统vim未正常退出产生的问题(can't write viminfo file /home/zhaoy/.viminfo)
    intellij idea根据mvn仓库添加或改变scala-sdk
    git拉项目和上传项目时遇到的一些问题
    简单的clone项目fromGitHub
    初始机器学习
  • 原文地址:https://www.cnblogs.com/diantao/p/5211780.html
Copyright © 2011-2022 走看看