Home Web Front-end JS Tutorial How to use JavaScript to implement drag-and-drop adjustment of table column width?

How to use JavaScript to implement drag-and-drop adjustment of table column width?

Oct 21, 2023 am 08:14 AM
javascript sheet Column width adjustment

如何使用 JavaScript 实现表格列宽拖拽调整功能?

How to use JavaScript to implement drag-and-drop adjustment of table column width?

With the development of Web technology, more and more data are displayed on web pages in the form of tables. However, sometimes the column width of the table cannot meet our needs, and the content may overflow or the width may be insufficient. In order to solve this problem, we can use JavaScript to implement the drag-and-drop adjustment function of the column width of the table, so that users can freely adjust the column width according to their needs.

To implement the drag-and-drop adjustment function of table column width, the following three main steps are required:

  1. Mouse event monitoring: It is necessary to add mouse event monitoring to the table in order to capture the user's operation behavior.
  2. Dynamic adjustment of column width: Dynamically adjust the width of table columns according to the user's drag operation.
  3. Record table status: Record the column width status adjusted by the user so that the adjustment results can be maintained after the page is refreshed or reloaded.

The following will introduce the implementation methods of the above three steps in detail and give corresponding code examples.

  1. Mouse event listening

First, add mousedown event listening to the table. When the user clicks on the edge of a table column, they can start dragging to adjust the column width. In the mousedown event handling function, the position of the mouse click needs to be recorded.

function tableMouseDown(event) {
  // 记录鼠标点击的位置
  const startX = event.clientX;
  // ...
}
Copy after login

Next, add the mousemove event listener to the document object. In the mousemove event handler function, you need to calculate the distance moved by the mouse and dynamically change the width of the table column.

function documentMouseMove(event) {
  // 计算鼠标移动的距离
  const distanceX = event.clientX - startX;
  // 动态改变表格列的宽度
  // ...
}
Copy after login

Finally, add a mouseup event listener for the document object. When the user releases the mouse, stop resizing the column width.

function documentMouseUp() {
  // 停止调整列宽
  // ...
}
Copy after login
  1. Dynamic adjustment of column width

In the mousemove event handler, dynamically adjust the width of the table column according to the user's drag operation. First, you need to determine which column is currently being dragged, which can be determined through the th element in the header of the table. Then, dynamically change the width of the table column based on the calculated mouse movement distance.

function documentMouseMove(event) {
  // 计算鼠标移动的距离
  const distanceX = event.clientX - startX;
  
  // 动态改变表格列的宽度
  const th = document.elementFromPoint(startX, event.clientY);
  const columnIndex = th.cellIndex;
  const table = th.parentNode.parentNode.parentNode;
  const cells = table.querySelectorAll(`tr th:nth-child(${columnIndex + 1}), tr td:nth-child(${columnIndex + 1})`);

  const newWidth = parseFloat(getComputedStyle(cells[0]).width) + distanceX;
  for (const cell of cells) {
    cell.style.width = `${newWidth}px`;
  }
}
Copy after login
  1. Record table status

In order to maintain the column width adjusted by the user after the page is refreshed or reloaded, we need to record the column width status of the table. You can use localStorage or cookie to achieve persistent data storage.

function documentMouseUp() {
  // 停止调整列宽
  // ...

  // 记录表格的列宽状态
  const columnWidths = {};
  const table = document.querySelector('table');
  const columns = table.querySelectorAll('th');
  for (const column of columns) {
    columnWidths[column.cellIndex] = parseFloat(getComputedStyle(column).width);
  }
  
  localStorage.setItem('columnWidths', JSON.stringify(columnWidths));
}
Copy after login

When the page loads, the saved column width state can be read from localStorage and applied to the table.

window.addEventListener('load', function() {
  const columnWidths = JSON.parse(localStorage.getItem('columnWidths'));
  if (columnWidths) {
    const table = document.querySelector('table');
    const columns = table.querySelectorAll('th');
    for (const [index, width] of Object.entries(columnWidths)) {
      columns[index].style.width = `${width}px`;
    }
  }
});
Copy after login

Through the above three steps, we can realize the drag and drop adjustment function of table column width. Users can freely adjust the column width of the table and optimize the display effect of the table according to actual needs. Hope this article is helpful to you!

The above is the detailed content of How to use JavaScript to implement drag-and-drop adjustment of table column width?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Steps to adjust the format of pictures inserted in PPT tables Steps to adjust the format of pictures inserted in PPT tables Mar 26, 2024 pm 04:16 PM

1. Create a new PPT file and name it [PPT Tips] as an example. 2. Double-click [PPT Tips] to open the PPT file. 3. Insert a table with two rows and two columns as an example. 4. Double-click on the border of the table, and the [Design] option will appear on the upper toolbar. 5. Click the [Shading] option and click [Picture]. 6. Click [Picture] to pop up the fill options dialog box with the picture as the background. 7. Find the tray you want to insert in the directory and click OK to insert the picture. 8. Right-click on the table box to bring up the settings dialog box. 9. Click [Format Cells] and check [Tile images as shading]. 10. Set [Center], [Mirror] and other functions you need, and click OK. Note: The default is for pictures to be filled in the table

How to set WPS value to automatically change color according to conditions_Steps to set WPS table value to automatically change color according to condition How to set WPS value to automatically change color according to conditions_Steps to set WPS table value to automatically change color according to condition Mar 27, 2024 pm 07:30 PM

1. Open the worksheet and find the [Start]-[Conditional Formatting] button. 2. Click Column Selection and select the column to which conditional formatting will be added. 3. Click the [Conditional Formatting] button to bring up the option menu. 4. Select [Highlight conditional rules]-[Between]. 5. Fill in the rules: 20, 24, dark green text with dark fill color. 6. After confirmation, the data in the selected column will be colored with corresponding numbers, text, and cell boxes according to the settings. 7. Conditional rules without conflicts can be added repeatedly, but for conflicting rules WPS will replace the previously established conditional rules with the last added rule. 8. Repeatedly add the cell columns after [Between] rules 20-24 and [Less than] 20. 9. If you need to change the rules, you can just clear the rules and then reset the rules.

How to make a table for sales forecast How to make a table for sales forecast Mar 20, 2024 pm 03:06 PM

Being able to skillfully make forms is not only a necessary skill for accounting, human resources, and finance. For many sales staff, learning to make forms is also very important. Because the data related to sales is very large and complex, and it cannot be simply recorded in a document to explain the problem. In order to enable more sales staff to be proficient in using Excel to make tables, the editor will introduce the table making issues about sales forecasting. Friends in need should not miss it! 1. Open [Sales Forecast and Target Setting], xlsm, to analyze the data stored in each table. 2. Create a new [Blank Worksheet], select [Cell], and enter [Label Information]. [Drag] downward and [Fill] the month. Enter [Other] data and click [

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Do you know how to sum a Word table? Do you know how to sum a Word table? Mar 21, 2024 pm 01:10 PM

Sometimes, we often encounter counting problems in Word tables. Generally, when encountering such problems, most students will copy the Word table to Excel for calculation; some students will silently pick up the calculator. Calculate. Is there a quick way to calculate it? Of course there is, in fact the sum can also be calculated in Word. So, do you know how to do it? Today, let’s take a look together! Without further ado, friends in need should quickly collect it! Step details: 1. First, we open the Word software on the computer and open the document that needs to be processed. (As shown in the picture) 2. Next, we position the cursor on the cell where the summed value is located (as shown in the picture); then, we click [Menu Bar

How to switch tables horizontally and vertically in word How to switch tables horizontally and vertically in word Mar 20, 2024 am 09:31 AM

Word software is indispensable to us and needs to be used frequently. I have learned how to edit tables using Word software before. However, if I accidentally edit the table in the horizontal and vertical directions, and I don’t want to waste time re-creating it, is it possible to change the horizontal and vertical directions of the table? Woolen cloth? The answer is of course yes. Next, the editor will introduce to you in detail how to swap tables horizontally and vertically in Word. Let us learn together. First, we need to swap the rows and columns of the Word table below. To do this, we need to first select the table entirely, then right-click and select the copy function. Step 2: After selecting copy, we minimize word, then open an Excel table, right-click, select paste, and paste it into Exc

What are the tips for novices to create forms? What are the tips for novices to create forms? Mar 21, 2024 am 09:11 AM

We often create and edit tables in excel, but as a novice who has just come into contact with the software, how to use excel to create tables is not as easy as it is for us. Below, we will conduct some drills on some steps of table creation that novices, that is, beginners, need to master. We hope it will be helpful to those in need. A sample form for beginners is shown below: Let’s see how to complete it! 1. There are two methods to create a new excel document. You can right-click the mouse on a blank location on the [Desktop] - [New] - [xls] file. You can also [Start]-[All Programs]-[Microsoft Office]-[Microsoft Excel 20**] 2. Double-click our new ex

How to insert automatic numbering or serial numbers into Word tables How to insert automatic numbering or serial numbers into Word tables Mar 20, 2024 am 09:30 AM

When we make tables, the first thing we think of is to use Excel software to make tables. But did you know that Word software is actually very convenient to make tables. Sometimes when we make tables in Word software, we need to enter serial numbers or numbers. , if you enter them one by one manually, it will be very troublesome. In fact, there is an operation in the word software that can automatically insert numbers or serial numbers. So let’s learn with the editor how to insert automatic numbering or serial numbers into Word tables. . 1. First create a Word document and insert a table. 2. Select the column or cell where you want to insert automatic serial numbers or numbers. 3. Click "Start" - "Number". 4. Select one of the style numbers. 5.

See all articles