zoukankan      html  css  js  c++  java
  • 用javaScript实现拖拽效果

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
            #box{
                position: absolute;
                width: 200px;
                height: 200px;
                background: red;
            }
        </style>
        <script>
            window.onload=function(){
                var drag=new Drag("box")
                drag.init();
            }
            //构造函数Drag
            function Drag(id){
                this.obj=document.getElementById(id);
                this.disX=0;
                this.disY=0;
            }
            Drag.prototype.init = function (){
                var me = this;
                this.obj.onmousedown = function (e){  
                    var e = e || event;
                    me.mouseDown(e);
                    // 阻止默认事件
                    return false;
                };
            };
            Drag.prototype.mouseDown=function(e){          
                var me=this;
                this.disX = e.clientX - this.obj.offsetLeft;
                this.disY = e.clientY - this.obj.offsetTop;
                document.onmousemove=function(e){
                    var e=e||window.event;
                    me.mouseMove(e);
                };
                document.onmouseup = function (){
                me.mouseUp();
             }
            }
            Drag.prototype.mouseMove = function (e){
                this.obj.style.left = (e.clientX - this.disX) + 'px';
                this.obj.style.top = (e.clientY - this.disY) + 'px';
            };
            Drag.prototype.mouseUp = function (){
                document.onmousemove = null; //如果不卸载这个事件的话,鼠标抬起后,移动鼠标,div依然会移动。
                document.onmouseup = null;
            };
  • 相关阅读:
    欧几里得方程 模幂运算 模乘运算 蒙哥马利模乘 素数测试
    HLG 1058workflow解题报告
    poj 3264Balanced Lineup解题报告
    JavaScript之HTMLCollection接口
    随记2(IE下调试Javascript)
    抽象类和接口
    JavaScript之字符串处理函数
    随记1
    多态
    自动内存管理
  • 原文地址:https://www.cnblogs.com/jcbo/p/6781532.html
Copyright © 2011-2022 走看看