• JavaScript学习笔记(八)拖放


    1. 元素跟随鼠标

    document.addEventListener('mousemove', function(event) {
      var myDiv = document.getElementById('myDiv')
      myDiv.style.left = event.clientX + 'px'
      myDiv.style.top = event.clientY + 'px'
    })

    2. 可拖动元素的事件

    var DragDrop = function () {
      var dragdrop = new EventTarget()
      var dragging = null
      var diffX = 0
      var diffY = 0
      function handleEvent(event) {
        var target = event.target
        switch(event.type) {
          case 'mousedown':
            if (target.className.indexOf('draggble') > -1) {
              dragging = target
              diffX = event.clientX - target.offsetLeft
              diffY = event.clientY - target.offsetTop
              dragdrop.fire({type: 'dragstart', target: dragging, x: event.clientX, y: event.clientY})
            }
            break
          case 'mousemove':
            if (dragging !== null) {
              dragging.style.left = (event.clientX - diffX) + 'px'
              dragging.style.top = (event.clientY - diffY) + 'px'
              dragdrop.fire({type: 'drag', target: dragging, x: event.clientX, y: event.clientY})
            }
            break
          case 'mouseup':
            dragging = null
            dragdrop.fire({type: 'dragend', target: dragging, x: event.clientX, y: event.clientY})
            break
        }
      }
      dragdrop.enable = function() {
        document.addEventListener('mousedown', handleEvent)
        document.addEventListener('mousemove', handleEvent)
        document.addEventListener('mouseup', handleEvent)
      }
      dragdrop.disable = function() {
        document.removeEventListener('mousedown', handleEvent)
        document.removeEventListener('mousemove', handleEvent)
        document.removeEventListener('mouseup', handleEvent)
      }
      return dragdrop
    }
    var dragdrop = DragDrop()
    dragdrop.addHandler('dragstart', function(event) {
      console.log('start', event)
    })
    dragdrop.addHandler('drag', function(event) {
      console.log('drag', event)
    })
    dragdrop.addHandler('dragend', function(event){
      console.log('end', event)
    })
    dragdrop.enable()

    参考: EventTarget

  • 相关阅读:
    java三层架构:持久层、业务层、表现层
    Spring:Spring JDBCTemplate & 声明式事务
    Spring:AOP
    Spring:IOC控制反转
    Mybatis: 加载策略及注解开发
    Mybatis 配置文件深入
    Mybatis:基本应用
    前后端项目接口联调
    springboot整合jsp
    IDEA出现URI is not registered (Settings | Languages & Frameworks | Schemas and DTDs)
  • 原文地址:https://www.cnblogs.com/zhoulixue/p/10780151.html
Copyright © 2020-2023  润新知