zoukankan      html  css  js  c++  java
  • 原生js拖拽

      好吧,js拖拽这个很多笔试面试都考过了,so,写一个练练手吧!

    function Drag(obj) {
    this.obj = obj;
    }
    Drag.prototype = {
    constructor : Drag,
    getInitPosition : function(e) {
    e = e || window.event;
    var eX, eY;
    if (e.pageX || e.pageY) {
    eX = e.pageX;
    eY = e.pageY;
    }
    eX = e.clientX;
    eY = e.clientY;
    var positionX = eX - this.obj.offsetLeft;
    var positionY = eY - this.obj.offsetTop;
    return {
    x : positionX,
    y : positionY
    }
    },
    getmouseCoordinate : function(e) {
    e = e || window.event;
    if (e.pageX || e.pageY) {
    return {
    x : e.pageX,
    y : e.pageY
    };
    }
    return {
    x : e.clientX + document.body.scrollLeft - document.body.clientLeft,
    y : e.clientY + document.body.scrollTop - document.body.clientTop
    };
    },
    initDrag : function() {
    var tempThis = this;
    this.obj.onmousedown = function(e) {
    var initP = tempThis.getInitPosition();
    document.onmousemove = function(e) {
    var moveP = tempThis.getmouseCoordinate();
    tempThis.obj.style.marginTop = moveP.y - initP.y + "px";
    tempThis.obj.style.marginLeft = moveP.x - initP.x + "px";
    }
    document.onmouseup = function() {
    document.onmousemove = null;
    document.onmouseup = null;
    }
    }
    }
    }
    var drag = document.getElementById("drag1");
    var dragElement = new Drag(drag);
    dragElement.initDrag();

      

  • 相关阅读:
    javascript与CSS复习(《精通javascript》)
    javascript改进表单
    javascript与CSS复习(三)
    javascript dom代码应用:简单的相册
    重新发明轮子之Draggable Elements
    《精通javascript》5,6章复习(三)
    我的JAVA之旅(五)继承
    全面学习DBMS包之UTL_FILE
    想法
    生活在上海
  • 原文地址:https://www.cnblogs.com/dunken/p/4365571.html
Copyright © 2011-2022 走看看