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

Native JavaScript implementation of progress bar

The specific code for JavaScript to implement the...

How to start the spring-boot project using the built-in linux system in win10

1. Install the built-in Linux subsystem of win10 ...

Record a slow query event caused by a misjudgment of the online MySQL optimizer

Preface: I received crazy slow query and request ...

A brief analysis of Vue's asynchronous update of DOM

Table of contents The principle of Vue asynchrono...

Velocity.js implements page scrolling switching effect

Today I will introduce a small Javascript animati...

Detailed explanation of Vue3's responsive principle

Table of contents Review of Vue2 responsive princ...

Analysis of Vue element background authentication process

Preface: Recently, I encountered a management sys...

Detailed steps for Python script self-start and scheduled start under Linux

1. Python automatically runs at startup Suppose t...

The difference and usage of distinct and row_number() over() in SQL

1 Introduction When we write SQL statements to op...

mysql5.7 installation and configuration tutorial under Centos7.3

This article shares the MySQL 5.7 installation an...

Implement QR code scanning function through Vue

hint This plug-in can only be accessed under the ...

Creative About Us Web Page Design

Unique “About”-Pages A great way to distinguish yo...

Introduction to useRef and useState in JavaScript

Table of contents 1. useState hook 2. useRef hook...

JS ES new features: Introduction to extension operators

1. Spread Operator The spread operator is three d...

WeChat applet development form validation WxValidate usage

I personally feel that the development framework ...