zoukankan      html  css  js  c++  java
  • js拖拽效果的原理及实现

    1. 原理


    JS 拖拽一个元素的原理:
    首先要明白三个值

    鼠标的位置A = {x, y}
    盒子的位置B = {x, y}
    鼠标在盒子内的距离C = {A.x - B.x, A.y - B.y}
    涉及到三个鼠标事件

    鼠标按下时,mousedown
    鼠标移动时,mousemove
    鼠标松开时,mouseup
    然后就可以开始讲明实现过程了

    鼠标按下的时候,计算出C,鼠标在盒子里距离(鼠标位置 - 盒子位置)
    鼠标移动的时候,更新盒子位置 B = A - C
    鼠标松开的时候,关闭2, 3过程的两个鼠标监听器
    ————————————————

    2. 代码实现

    html

    <div class="box">
    
    </div>

    css

    .box {
        position: absolute;
         100px;
        height: 100px;
        left: 10px;
        top: 10px;
        background-color: beige;
    }
    
    .box:hover {
        cursor: move;
    }
    

     js

    var box = document.querySelector('.box')
    
    // 获取元素的样式
    var getStyle = function(element){
        return window.getComputedStyle(box, null)
    }
    
    // 获取目标元素的位置
    var getTargetPos = function(elem) {
        var elemStyle = getStyle(elem)
        var pos = {
            x: parseInt(elemStyle.left.slice(0, -2)),
            y: parseInt(elemStyle.top.slice(0, -2))
        }
        return pos
    }
    
    // 设置目标元素的位置
    var setTargetPos = function(elem, pos) {
        elem.style.left = pos.left
        elem.style.top = pos.top
        return elem
    }
    
    box.addEventListener('mousedown', function(event) {
        var divPos = getTargetPos(box)
        var mousePos = {
            x: event.clientX,
            y: event.clientY
        }
        // 鼠标按下的时候,记录鼠标在div内部的距离
        var innerDis = {
            x: event.clientX - divPos.x,
            y: event.clientY - divPos.y
        }
    
        var move = function(event) {
            // 鼠标移动到的新位置 - 鼠标在div的内部距离 即是拖动元素的新位置
            setTargetPos(box, {
                left: (event.clientX - innerDis.x) + 'px',
                top: (event.clientY - innerDis.y) + 'px',
            })
        }
    
        var end = function() {
            document.removeEventListener('mousemove', move)
            document.removeEventListener('mouseup', end)
        }
    
        // 必须绑定在document对象上,如果绑定在box对象上,当鼠标脱快了移出box盒子时,就会产生BUG
        document.addEventListener('mousemove', move, false)
        document.addEventListener('mouseup', end, false)
    

      

     

  • 相关阅读:
    hdu 3577 线段树
    hdu 5316 Magician 线段树
    POJ3468 本来是一道线段树
    hdu 3183 st表
    hdu 5285 BestCoder Round #48 ($) 1002 种类并查集
    hdu 5282 序列计数
    zoj 2432 模板LCIS
    hdu 1052 贪心
    Angular实践----定制你自己的指令
    Angular实践----理解数据绑定过程
  • 原文地址:https://www.cnblogs.com/zqm0924/p/12642591.html
Copyright © 2011-2022 走看看