Home Web Front-end JS Tutorial Detailed explanation of examples of changing DIV by dragging the mouse with the mouse

Detailed explanation of examples of changing DIV by dragging the mouse with the mouse

Jul 19, 2017 pm 05:36 PM
element Change Web page

1. First implementation

1.1 html code

<html xmlns="www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>div change width by drag</title><script src="../jQuery/jquery-1.8.3.min.js?1.1.11" type="text/javascript"></script></head><body><h1>div change width by drag</h1><div id="pos" style="color:red"></div><div id="myDiv" style="border:2px solid red;width:300px;height:50px;margin-left: 100px;margin-top: 20px"></div></body></html>
Copy after login

1.2 js code

          var eleLeft = $('#myDiv').offset().left;var isMouseDown = false;var borderLen = 4; //左右边框                
                $('#myDiv').bind({
                    mousedown:function(e){var ele = $(this);var rightPos = eleLeft + ele.width() + borderLen;if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            isMouseDown = true;

                        }
                    },
            
                    mousemove:function(e){var ele =  $(this);var rightPos = eleLeft + ele.width() + borderLen;
                        $(&#39;#pos&#39;).text("x:"+e.pageX + " eleLeft:"+eleLeft+" rightPos:"+rightPos);if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            ele.css(&#39;cursor&#39;,&#39;e-resize&#39;);
                        }else{if(!isMouseDown){
                                ele.css(&#39;cursor&#39;,&#39;auto&#39;);
                            }
                        }if(isMouseDown){
                            ele.width((e.pageX-eleLeft-borderLen)+&#39;px&#39;);  //新鼠标位置-div距左-borderLen                        }
                    },
                    mouseup:function(e){
                        isMouseDown = false;
                    }
                });
Copy after login

1.3 Result

You can only drag to the left to make the div width smaller, dragging to the right is useless! The reason is that the mousemove event of dragging the mouse to the right cannot be captured by the div. It's also hard to stop while dragging! So it has to be improved.

2. Improve again

          $(&#39;#myDiv&#39; ele = $( rightPos = eleLeft + ele.width() +(rightPos-5 <= e.pageX && e.pageX <== &#39;body&#39; ele = $(&#39;#myDiv&#39; rightPos = eleLeft + ele.width() +&#39;#pos&#39;).text("x:"+e.pageX + " eleLeft:"+eleLeft+" rightPos:"+(rightPos-5 <= e.pageX && e.pageX <=&#39;cursor&#39;,&#39;e-resize&#39;(!&#39;cursor&#39;,&#39;auto&#39;-eleLeft-borderLen)+&#39;px&#39;);  =
Copy after login

This time the above problem is solved. You can drag to the right and stop at any time. Are you done here? NO!

What happens when I introduce another div and prevent the mouseup event from bubbling? The answer is that after dragging to this other div and releasing the mouse, it cannot be stopped!

<div id="otherDiv" style="border: 2px solid blue;width: 200px;height: 200px;margin-left: 400px"></div>
Copy after login

         $('#otherDiv').mouseup(function(e){//e.preventDefault(); //阻止默认行为e.stopPropagation(); //阻止事件冒泡(导致body捕获不到mouseup事件)});
Copy after login

3. Perfect solution

Drag stop may be affected by other elements Interference, how to solve it? Thinking about the functions of some pop-up layers that can be hidden by clicking on other places, I thought of adding a mask layer so that the mouseup event can always be responded to. Isn't it done?

        $('#myDiv').bind({
                    mousedown:function(e){var ele = $(this);var rightPos = eleLeft + ele.width() + borderLen;if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            isMouseDown = true;//创建遮罩层,防止mouseup事件被其它元素阻止冒泡,导致mouseup事件无法被body捕获,导致拖动不能停止var bodyWidth = $(&#39;body&#39;).width();var bodyHeight = $(&#39;body&#39;).height();
                            $(&#39;body&#39;).append(&#39;<div id="mask" style="opacity:0.2;top:0px;left:0px;background-color:green;position:absolute;z-index:9999;width:&#39;+bodyWidth+&#39;px;height:&#39;+bodyHeight+&#39;px;"></div>');
                        }
                    }
                });

                $('body').bind({
                    mousemove:function(e){var ele = $('#myDiv');var rightPos = eleLeft + ele.width() + borderLen;
                        $('#pos').text("x:"+e.pageX + " eleLeft:"+eleLeft+" rightPos:"+rightPos);if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            ele.css(&#39;cursor&#39;,&#39;e-resize&#39;);
                        }else{if(!isMouseDown){
                                ele.css(&#39;cursor&#39;,&#39;auto&#39;);
                            }
                        }if(isMouseDown){
                            ele.width((e.pageX-eleLeft-borderLen)+&#39;px&#39;); 
                        }
                    },
                    mouseup:function(e){
                        isMouseDown = false;
                        $(&#39;#mask&#39;).remove();
                    }
                });

                $(&#39;#otherDiv&#39;).mouseup(function(e){//e.preventDefault(); //阻止默认行为e.stopPropagation(); //阻止事件冒泡(导致body捕获不到mouseup事件)});
Copy after login

4. Complete code and final effect

div change width by drag
        

div change width by drag

        
<div id="otherDiv" style="border: 2px solid blue;width: 200px;height: 200px;margin-left: 400px"></div>
Copy after login

The above is the detailed content of Detailed explanation of examples of changing DIV by dragging the mouse with the mouse. 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)

How to send web pages to desktop as shortcut in Edge browser? How to send web pages to desktop as shortcut in Edge browser? Mar 14, 2024 pm 05:22 PM

How to send web pages to the desktop as a shortcut in Edge browser? Many of our users want to display frequently used web pages on the desktop as shortcuts for the convenience of directly opening access pages, but they don’t know how to do it. In response to this problem, the editor of this issue will share the solution with the majority of users. , let’s take a look at the content shared in today’s software tutorial. The shortcut method of sending web pages to the desktop in Edge browser: 1. Open the software and click the "..." button on the page. 2. Select "Install this site as an application" in "Application" from the drop-down menu option. 3. Finally, click it in the pop-up window

How to set up web page automatic refresh How to set up web page automatic refresh Oct 26, 2023 am 10:52 AM

To set the automatic refresh of a web page, you can use the HTML "meta" tag, the JavaScript "setTimeout" function, the "setInterval" function or the HTTP "Refresh" header. Detailed introduction: 1. Use the "meta" tag of HTML. In the "<head>" tag of the HTML document, you can use the "meta" tag to set the automatic refresh of the web page; 2. The "setTimeout" function of JavaScript, etc.

What should I do if the images on the webpage cannot be loaded? 6 solutions What should I do if the images on the webpage cannot be loaded? 6 solutions Mar 15, 2024 am 10:30 AM

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

Possible reasons why the network connection is normal but the browser cannot access the web page Possible reasons why the network connection is normal but the browser cannot access the web page Feb 19, 2024 pm 03:45 PM

The browser cannot open the web page but the network is normal. There are many possible reasons. When this problem occurs, we need to investigate step by step to determine the specific cause and solve the problem. First, determine whether the webpage cannot be opened is limited to a specific browser or whether all browsers cannot open the webpage. If only one browser cannot open the web page, you can try to use other browsers, such as Google Chrome, Firefox, etc., for testing. If other browsers are able to open the page correctly, the problem is most likely with that specific browser, possibly

How to change the starting delivery price of Meituan Takeout merchant version How to change the starting delivery price of Meituan Takeout merchant version Mar 27, 2024 pm 07:20 PM

In the operation process of the Meituan Takeout Merchant Edition, the setting of the starting delivery price is a crucial link. A reasonable starting delivery price can not only help merchants control costs, but also increase order amounts to a certain extent, thus increasing overall revenue. However, many merchants don’t know much about how to modify the minimum delivery price. So in the following article, the editor of this website will bring you detailed starting price setting guide for merchants. If you want to know more, come to the following article to find out! In the Meituan Takeout Merchant Center, log in and enter the store settings, then select store management. In the switch navigation at the top of the store management page, select delivery information, and then click Add Delivery Area to complete the operation. Once you add a location, the corresponding shipping costs will automatically appear. After completing your order, you will receive

What to do if the webpage cannot be opened What to do if the webpage cannot be opened Feb 21, 2024 am 10:24 AM

How to solve the problem of web pages not opening With the rapid development of the Internet, people increasingly rely on the Internet to obtain information, communicate and entertain. However, sometimes we encounter the problem that the web page cannot be opened, which brings us a lot of trouble. This article will introduce you to some common methods to help solve the problem of web pages not opening. First, we need to determine why the web page cannot be opened. Possible reasons include network problems, server problems, browser settings problems, etc. Here are some solutions: Check network connection: First, we need

How to open php on the web page How to open php on the web page Mar 22, 2024 pm 03:20 PM

Executing PHP code in a web page requires ensuring that the web server supports PHP and is properly configured. PHP can be opened in three ways: * **Server environment:** Place the PHP file in the server root directory and access it through the browser. * **Integrated Development Environment: **Place PHP files in the specified web root directory and access them through the browser. * **Remote Server:** Access PHP files hosted on a remote server via the URL address provided by the server.

How to use CSS to create a web page loading progress bar implementation steps How to use CSS to create a web page loading progress bar implementation steps Oct 26, 2023 am 11:00 AM

Implementation steps of how to use CSS to create a web page loading progress bar In modern web design, loading speed is crucial to user experience. In order to improve the user experience, you can use CSS to create a web page loading progress bar so that users can clearly understand the web page loading progress. This article will introduce the implementation steps of using CSS to create a web page loading progress bar, and provide specific code examples. Step 1: HTML structure First, you need to add a div element representing the progress bar in HTML, as shown below: &lt;divclass=&q

See all articles