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();

      

  • 相关阅读:
    [SCOI2003]严格N元树
    CF280 C. Game on Tree
    [HDU2281]Square Number
    [HDU5391]Zball in Tina Town
    [HDU3988]Harry Potter and the Hide Story
    [HDU5794]A Simple Chess
    [HDU5451]Best Solver
    [HDU1724]Ellipse
    [HDU6304]Chiaki Sequence Revisited
    [HDU6343]Graph Theory Homework
  • 原文地址:https://www.cnblogs.com/dunken/p/4365571.html
Copyright © 2011-2022 走看看