HTML drag and drop function implementation code

HTML drag and drop function implementation code

Based on Vue

The core idea of ​​this function is to control the left and top margins of the node on the page through JavaScript code. Different style positioning methods have different solutions.

This solution adopts position: absolute positioning solution

CSS style core code

// Parent container core style width: 100%;
  height: 100%;
//Subcontainer core style position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);

The parent container occupies the entire visible range of the browser through the width && height fields, and the child container enables absolute positioning within the parent container through position: absolute attribute, and controls the absolute position of the child container within the parent container through top && left && transform: translate(-50%, -50%) attributes.

JavaScript core code for logic control

First, let's break down the steps and corresponding events required to achieve node movement.

  • When a child container is created, it is positioned absolutely within the parent container
  • When the mouse button is pressed, the onmousedown event
  • When the mouse moves, onmousemove event
  • When the mouse button is released, the onmouseup event

As long as you use the three events onMousedown, onMousemove and onMouseup, you can achieve the simplest movement

/*
* Get the top and left position of the child container relative to the parent container when the child container is created */

mounted () {
  this.left = this.$refs.fatherBox.offsetLeft
  this.top = this.$refs.fatherBox.offsetTop
}
/*
* When the mouse is pressed* 1. Enable the flag that allows child containers to move
* 2. Record the location information when the mouse is clicked*/

mouseDown (e) {
  // Set the flag to allow pop-up window to move
  this.moveFlag = true
  // Save the starting position of the mouse this.startLeft = e.clientX - this.left
  this.startTop = e.clientY - this.top
}
/*
* When the mouse moves* 1. Determine whether the flag allows the child container to move* 2. Set the left position of the pop-up box* 3. Set the right position of the pop-up box*/

move (e) {
  // Check if flag allows movement if (!this.moveFlag) return

  // Set the left position of the bullet box this.left = e.clientX - this.startLeft
  // Set the right position of the bullet box this.top = e.clientY - this.startTop

}
/*
* When the mouse button is released* 1. Turn off the flag that allows child containers to move
*/

mouseUp (e) {
  this.flag = false
}

Through these methods, you can get the top and left offsets of the mouse when the mouse is pressed and moved. By exposing this offset to the parent component, the parent component sets the top and left values ​​of the child component in real time to make the child container follow the movement of the mouse.

Parent component code

The parent component sets the ref and zIndex values ​​of the child component, and the backValue method of the parent component receives the zIndex value from the child component, and uses the zIndex to identify the specific child component instance.

/*
* Parent component code snippet jsx version */

export default {
  props: {
    playList: {
      type: Array,
      required: true
    }
  },
  render () {
    return (
      <div style={{width: '100%', height: '100%'}} ref={'father'}>
        {
          this.playList && this.playList.map((item, index) => {
            return (
              <ChildComponents
                key={index}
                ref={index}
                zIndex={index}
                visible={true}
                backValue={this.backValue}
                info={item}
                width={600}
                height={400}
              />
            )
          })
        }
      </div>
    )
  },
  methods: {
    backValue (left, top, zIndex) {
      this.$refs[zIndex].$el.style.top = `${top}px`
      this.$refs[zIndex].$el.style.left = `${left}px`
    }
  }
}
<!-- Parent component code snippet vue file version -->

<template>
  <div
    ref="father"
    style"width: 100%, height: 100%"
  >
    <ChildComponents
      v-for="(item, index) in playList"
      :key="index"
      :ref="index"
      :visible="true"
      :z-index="index"
      :back-value="backValue"
      :info="item"
      :close="close"
      :width="600"
      :height="400"
    />
  </div>
</template>
<script>
export default {
  components:
    VideoPlayerModal
  },
  props: {
    playList: {
      type: Array,
      required: true
    }
  },
  methods: {
    backValue (left, top, zIndex) {
      this.$refs[zIndex][0].$el.style.top = `${top}px`
      this.$refs[zIndex][0].$el.style.left = `${left}px`
    }
  }
}
</script>

Set the fence range of the child component

This function only needs to determine whether the top and left of the child container are beyond the visible range of the browser in the onmousemove event.

/*
* 1. this.width data is the width value passed in by the parent component, or the default value set by the child component itself* 2. this.height data is the height value passed in by the parent component, or the default value set by the child component itself*/

move (e) {
  // Check if flag allows movement if (!this.moveFlag) return

  // Determine whether it exceeds the left view if (this.$refs.fatherBox.offsetLeft < this.width / 2) {
        // Disable the pop-up box from moving this.moveFlag = false
        // Set the left position of the bullet box this.left = this.width / 2 + 10
        // Call the callback function to expose the offset to the parent component this.backValue(this.left, this.top, this.zIndex)
        return
      }

      // Determine whether it exceeds the right view if (this.$refs.fatherBox.offsetLeft > document.body.clientWidth - this.width / 2) {
        // Disable the pop-up box from moving this.moveFlag = false
        // Set the right position of the bullet box this.left = document.body.clientWidth - this.width / 2 - 10
        // Call the callback function to expose the offset to the parent component this.backValue(this.left, this.top, this.zIndex)
        return
      }

      // Determine whether it exceeds the top view if (this.$refs.fatherBox.offsetTop < this.height / 2 + 70) {
        // Disable the pop-up box from moving this.moveFlag = false
        // Set the top position of the bullet box this.top = this.height / 2 + 70 + 10
        // Call the callback function to expose the offset to the parent component this.backValue(this.left, this.top, this.zIndex)
        return
      }

      // Determine whether it exceeds the bottom view if (this.$refs.fatherBox.offsetTop > document.body.clientHeight - this.height / 2 - 50) {
        // Disable the pop-up box from moving this.moveFlag = false
        // Set the bottom position of the bullet box this.top = document.body.clientHeight - this.height / 2 - 50 - 10
        // Call the callback function to expose the offset to the parent component this.backValue(this.left, this.top, this.zIndex)
        return
      }

      // Set the left position of the bullet box this.left = e.clientX - this.startLeft
      // Set the right position of the bullet box this.top = e.clientY - this.startTop

      // Call the callback function to expose the offset to the parent component this.backValue(this.left, this.top, this.zIndex)
}

The subcomponent also needs to set an onmouseout event when the mouse exceeds the subcontainer to prevent unexpected bugs.

mouseOut (e) {
  this.moveFlag = false
}

This is the end of this article about HTML drag-and-drop function. For more relevant HTML drag-and-drop function content, please search 123WORDPRESS.COM’s previous articles or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

<<:  CSS tips for implementing Chrome tab bar

>>:  Multiple ways to implement two-column layout with fixed width on the left and adaptive width on the right using CSS

Recommend

How to isolate users in docker containers

In the previous article "Understanding UID a...

Detailed explanation of CSS3 rotating cube problem

3D coordinate concept When an element rotates, it...

MySQL Series 10 MySQL Transaction Isolation to Implement Concurrency Control

Table of contents 1. Concurrent access control 2....

How to enable remote access in Docker

Docker daemon socket The Docker daemon can listen...

HTML+CSS makes div tag add delete icon in the upper right corner sample code

1. Requirements description Display the delete ic...

Detailed explanation of a method to rename procedure in MYSQL

Recently I have used the function of renaming sto...

Analysis of the operating principle and implementation process of Docker Hub

Similar to the code hosting service provided by G...

Monitor changes in MySQL table content and enable MySQL binlog

Preface binlog is a binary log file, which record...

Two ways to prohibit clearing the input text input cache in html

Most browsers will cache input values ​​by defaul...

MySQL InnoDB transaction lock source code analysis

Table of contents 1. Lock and Latch 2. Repeatable...

Example of converting spark rdd to dataframe and writing it into mysql

Dataframe is a new API introduced in Spark 1.3.0,...

Detailed explanation of the basic usage of the img image tag in HTML/XHTML

The image tag is used to display an image in a we...

Linux command line operation Baidu cloud upload and download files

Table of contents 0. Background 1. Installation 2...