JavaScript offset implements mouse coordinate acquisition and module dragging within the window

JavaScript offset implements mouse coordinate acquisition and module dragging within the window

offset

Offset is the offset. Using the offset series of related properties, you can dynamically obtain the position (offset), size, etc. of the element, such as:
Get the size (width and height) of the element from the position of the positioned parent element
Note: The returned value does not have a unit.

Commonly used attributes of the offset series include:
element.offsetParent
Returns the element that is the parent of this element with positioning. If the parent element is not positioned, it returns body
Note that there is an essential difference between parentNode and offsetParent: parentNode returns the direct parent element, while offsetParent returns the parent element with positioning.
element.offsetTop
Returns the element with the offset above the parent element.
element.offsetLeft
Returns the element with the offset of the positioned parent's left border
element.offsetWidth
Returns the width of the content area including padding, borders, and content area. The returned value does not include units.
element.offsetHeight
Returns the height of the element including padding, border, and content area. The returned value does not include units.

The difference between offset and style

offset style
offset can get the style value in any style sheet style can only get the style value in the inline style sheet, and cannot get the embedded style
The values ​​obtained by the offset series are unitless. style.width gets a string with units
offsetWidth includes padding+border+width style.width gets the value excluding padding and border
OffsetWidth and other properties are read-only properties, which can only be obtained but not assigned. The style attribute is a read-write attribute. style.width can be obtained or assigned.
When you only want to get the size and position of an element, it is more appropriate to use offset If you want to modify the style of an element, it is more appropriate to use style

Case 1: Real-time display of mouse coordinates

Demo

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Getting the mouse position-01</title>
		<style>
			.box {
				width: 500px;
				height: 500px;
				background-color: #55aaff;
				margin-left: 50px;
			}
		</style>
	</head>
	<body>
		<p>Get the mouse coordinates in the box</p>
		<div class="box"></div>
		<script>
			// Click in the box and want to get the distance between the mouse and the box // Implementation:
			// 1. Get the coordinates of the mouse on the page, e.pageX, e.pageY
			// 2. Get the distance from the box to the page, box.offsetLeft, box.offsetTop
			// 3. Subtracting the two will give you the coordinates of the mouse in the box // Let's see the implementation process below!
			const box = document.querySelector(".box");
			box.addEventListener("mousemove", function(e) {
				// console.log(e.pageX, e.pageY);
				// console.log(box.offsetLeft, box.offsetTop);
				const x = e.pageX - this.offsetLeft;
				const y = e.pageY - this.offsetTop;
				box.textContent = `x: ${x}, y: ${y}`;
			});
		</script>
	</body>
</html>

Case 2: Drag module

Demo

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Module Drag-02</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .login,
      .modal {
        display: none;
      }
      .login {
        width: 512px;
        height: 280px;
        position: fixed;
        border: #ebebeb solid 1px;
        left: 50%;
        top: 50%;
        background-color: #fff;
        box-shadow: 0 0 20px #ddd;
        z-index: 999;
        transform: translate(-50%, -50%);
        text-align: center;
      }
      .modal {
        position: absolute;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background-color: rgba(0, 0, 0, 0.3);
        z-index: 998;
      }
      .login-content {
        margin: 100px auto;
        text-align: center;
      }
      .login-content h3:hover,
      .closeBtn:hover {
        cursor: pointer;
      }
      .closeBtn {
        position: absolute;
        right: 10px;
        top: 10px;
      }
      .login h4 {
        margin-top: 10px;
      }
      .login h4:hover {
        cursor: move;
      }
    </style>
  </head>
  <body>
    <div class="login-content">
      <h3 id="openLogin">Click to pop up the simulation box</h3>
    </div>
    <div class="login">
      <div class="closeBtn" id="closeBtn">Close</div>
      <h4 class="loginHeader">Click me to drag</h4>
    </div>
    <div class="modal"></div>
    <script>
      // Get element const login = document.querySelector(".login");
      const modal = document.querySelector(".modal");
      const closeBtn = document.querySelector("#closeBtn");
      const openLogin = document.querySelector("#openLogin");
      // Click the display element openLogin.addEventListener("click", () => {
        modal.style.display = "block";
        login.style.display = "block";
      });
      closeBtn.addEventListener("click", () => {
        modal.style.display = "none";
        login.style.display = "none";
      });
      // Implement the drag and drop function // 1. Press the mouse to get the coordinates of the mouse in the box const loginHeader = document.querySelector(".loginHeader");
      loginHeader.addEventListener("mousedown", function (e) {
        const x = e.pageX - login.offsetLeft;
        const y = e.pageY - login.offsetTop;
        const move = function (e) {
          login.style.left = `${e.pageX - x}px`;
          login.style.top = `${e.pageY - y}px`;
        };
        // 2. Move the mouse document.addEventListener("mousemove", move);
        document.addEventListener("mouseup", function () {
          document.removeEventListener("mousemove", move);
        });
      });
    </script>
  </body>
</html>

This is the end of this article about using JavaScript offset to get mouse coordinates and drag modules within the window. For more information about using JavaScript to get mouse coordinates and drag modules within the window, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example of how to get the distance between the mouse position and the browser window using JS
  • JS determines the direction of the mouse entering the container and the problem of window.open new window being blocked
  • Detailed explanation of the example of JS implementing a pop-up floating window (supporting mouse dragging and closing)
  • JS implements the method of simulating mouse movement when the window is loaded
  • javascript window width and height, mouse position, scroll height (detailed analysis)
  • JavaScript implements mouse control of free moving window

<<:  How to insert 10 million records into a MySQL database table in 88 seconds

>>:  Nginx uses reverse proxy to implement load balancing process analysis

Recommend

Simplify complex website navigation

<br />Navigation design is one of the main t...

Install Windows Server 2019 on VMware Workstation (Graphic Tutorial)

If prompted to enter a key, select [I don’t have ...

JSONP cross-domain simulation Baidu search

Table of contents 1. What is JSONP 2. JSONP cross...

Creative opening effect achieved by combining CSS 3.0 with video

Let me share with you a creative opening realized...

Repair solution for inconsistent MySQL GTID master and slave

Table of contents Solution 1: Rebuild Replicas Pr...

How to manage multiple projects on CentOS SVN server

One demand Generally speaking, a company has mult...

Solution to Docker disk space cleaning

Some time ago, I encountered the problem that the...

Introducing multiple custom fonts in CSS3

Today I found a problem in HTML. There are many d...

Vue implements form data validation example code

Add rules to the el-form form: Define rules in da...

Install ethereum/Ethereum from scratch under CentOS7

Table of contents Preface Add sudo write permissi...

OpenLayers realizes the method of aggregate display of point feature layers

Table of contents 1. Introduction 2. Aggregation ...

How to use nginx to configure access to wgcloud

The nginx configuration is as follows: Such as ht...

A brief introduction to web2.0 products and functions

<br />What is web2.0? Web2.0 includes those ...