Implementation of drag-and-drop effects in PC web pages using javascript _ javascript skills

Source: Internet
Author: User
This article mainly introduces the information about how javascript achieves drag-and-drop effects on PC web pages. For more information, refer to the following years. I participated in the design and development of a real estate network project. I am in charge of front-end work, because the project manager has high requirements, I have referenced many excellent functions of real estate websites and want to bring together the excellent designs and ideas of others. The design draft and function implementation at that time were as follows, I just changed it and changed it. A good result today may be pushed back the next day. Forget it. Let's talk about the cases we want to explain today, I don't know if you have visited Soufun (no advertisement at all, Soufun, you can pay for ads). One function product manager is particularly fond of it, that is, the following:

This is the current effect, which may have been changed. The original effect is that the figure in it can be dragged up, down, left, and right. Then the building number displayed on the house is moved along with the picture, at that time, the js capability was not enough to meet the requirements of the project manager. However, the project manager pushed down the effect and changed it to another effect.

Although the project manager didn't want this effect, I left a section in my mind and I can't forget it until today.

Well, this is my original intention to write this blog today. I hope to provide some ideas for those who want to achieve this drag-and-drop effect but do not know how to implement it, there are many ways to implement drag-and-drop operations without leaving regret for your youth. Here we will only introduce one method in JavaScript, so let's take a look at the principles!

Now, the stem is finished. Let's get started with the question. First, we need to understand what drag is. You know, I know, but I still want to describe it:

Drag and Drop is a container. You can drag around the page with your mouse. It is nonsense. The exact description should be: move the mouse over the container, and then press the mouse. Be sure to press it, then drag the mouse and the container can run with the mouse. When the mouse is released, the container will stop there. In reality, there is a box on the table. I put my hands on the box and then move the box, stop the box with your hands and pull it away. The box won't move anymore. You can understand it!

Don't think that the above is a bunch of nonsense. We can get a lot of information, which is summarized as follows:

Drag = mouse Press + mouse move + mouse up

This completes a drag-and-drop task. It turns out that this is the principle of drag-and-drop. You can simulate the drag-and-drop effect by naturally implementing the above three actions, corresponding to the syntax in JavaScript, these three actions need to be implemented:

Onmousedown, onmousemove, onmouseup

The implementation code should be:

obj.onmousedown = function(ev){   obj.onmousemove = function(ev){    } ;   obj.onmouseup = function(ev){      };   }

Why do you want to write the next two actions? Let's have a good review. Well, the first step is the general idea. In the next step, we need to consider how to move the object with the mouse, the idea is probably like this:

First, the object needs to be located, because we need to operate its left and top values to move it. Then, we need to consider the mouse, and the mouse shift, there will be a distance, if we know how far the mouse is moving and then give the distance to the object, does the object move the same distance as the mouse? Isn't that dragging? Haha, I think it's cute ~ Now the question is how to get the mouse distance. If you need to learn more, please review the box model. I will not talk about it here. Many great gods also have related blogs, I will use a picture to represent it:

Note: The Blue Box indicates the screen width and height, and the black thick box indicates the browser's visible area width and height (the browser's zoom-in effect). The black box indicates the object to be dragged by the mouse. We can see that we can get the coordinates of the mouse, you can use event. clientX, event. clientY;

The general principles of computing can be referred:

Note: The initial position is on the left, the target position on the right, the cursor position on the origin, the visible width of the browser, and the drag object on the black box, get the final position of the mouse, subtract the difference between the mouse and the object, and assign the value to the top and left of the object. You can also get the difference between the positions of the mouse and use the initial top, when the left value is added with the difference value, we use the first and second values. You can try it yourself:

 obj.onmousedown = function(ev){  var ev = ev || event;  var disX = ev.clientX - this.offsetLeft,disY = ev.clientY - this.offsetTop;   document.onmousemove = function(ev){    var ev = ev || event;    obj.style.left = ev.clientX - disX + 'px';    obj.style.top = ev.clientY - disY + 'px';  };  document.onmouseup = function(ev){    var ev = ev || event;    document.onmousemove = document.onmouseup = null;  };}

Here, we will explain that onmousemove and onmouseup use the document object instead of the obj object because if the obj object is used, the mouse is fine inside the obj object. If it is outside the obj object, dragging and dropping will be weird, you can also change it to obj to try it out. At last, we can clear all events when the mouse is up;

The above basic drag is complete, but careful students will certainly ask, if there is a text on the page, the drag object will select the text, this effect is not strange, yes, this is because the browser's default selection event is triggered during the drag and drop operation. Therefore, we need to clear this default event during the drag and drop operation. How can we clear it?

The following is a Compatibility Statement:

If (ev. stopPropagation) {ev. stopPropagation ();} else {ev. cancelBubble = true; // compatible with IE} // abbreviated to ev. stopPropagation? Ev. stopPropagation (): ev. cancelBubble = true;

Put the above Code under onmousedown, press the mouse to clear the default events of the browser, and the text will not be selected. Well, a simple drag-and-drop effect is complete, of course, you can't see the effect now. The reason why you don't give the demo link is to let yourself try to write it, which is more impressive,

Okay, that's the problem again. Is it all done here ?...... According to my own style, of course not, dry goods are still behind!

If I want to achieve this effect, it is in this large container (can be box or document), how can we drag and drop objects without running them? In other words, drag it to the edge and it will not move. Yeah, is it the effect that many people want to achieve? haha, let's look at the implementation principle:

In real life, an object cannot run out of a box because of a wall. If we can simulate this wall, we can frame it, what should we do with this wall? We can change our thinking. When dragging an object to the edge, for example, dragging it to the right, we fix its left, so we can no longer move it to the right, because the left value cannot be added, so drag it to the bottom. Similarly, if we fix the top value, we won't be able to drag it down. Do you understand?

The final result is as follows:

// If (obj. offsetLeft <= 0) {obj. style. left = 0 ;}; // if (obj. offsetLeft> = pWidth-oWidth) {obj. style. left = pWidth-oWidth + 'px ';}; // The above if (obj. offsetTop <= 0) {obj. style. top = 0 ;}; // The following if (obj. offsetTop> = pHeight-oHeight) {obj. style. top = pHeight-oHeight + 'px ';};

Note:PWidth, pHeight indicates the width and height of the parent element (here it indicates the width and height limit relative to the parent), oWidth, oheimpaired indicates the width and height of the drag Element

Finally, I organized the entire drag-and-drop code:

/* Parameter description: absolute positioning of the element. Relative positioning of the parent level. If the parent level is window, you do not need to pass a parameter, indicating that the parent level is window, drag an object to the window range to pass two parameters. The parent level is the second parameter, and the drag parameter of the object relative to the parent level is the id value */function drag (obj, parentNode) {var obj = document. getElementById (obj); if (arguments. length = 1) {var parentNode = window. self; var pWidth = parentNode. innerWidth, pHeight = parentNode. innerHeight;} else {var parentNode = document. getElementById (parentNode); var pWidth = parentNode. offset Width, pHeight = parentNode. offsetHeight;} obj. onmousedown = function (ev) {var ev = ev | event; var disX = ev. clientX-this. offsetLeft, disY = ev. clientY-this. offsetTop; var oWidth = obj. offsetWidth, oHeight = obj. offsetHeight; // prevents the bubble time ev. stopPropagation? Ev. stopPropagation (): ev. cancelBubble = true; document. onmousemove = function (ev) {var ev = ev | event; obj. style. left = ev. clientX-disX + 'px '; obj. style. top = ev. clientY-disY + 'px '; // left if (obj. offsetLeft <= 0) {obj. style. left = 0 ;}; // if (obj. offsetLeft> = pWidth-oWidth) {obj. style. left = pWidth-oWidth + 'px ';}; // The above if (obj. offsetTop <= 0) {obj. style. top = 0 ;}; // The following if (obj. offsetTop> = pHeight-oHeight) {obj. style. top = pHeight-oHeight + 'px ';};}; document. onmouseup = function (ev) {var ev = ev | event; document. onmousemove = document. onmouseup = null ;};}}

Note: The processing result here is that if a parameter is passed, the relative object is a window object. If two parameters are passed, the first parameter is the drag object, and the second parameter is the parent parameter.

As I said at the beginning, the drag-and-drop effect of Soufun is a knot in my mind. I wrote a similar effect for your reference, because I didn't buy a server, therefore, I will not show the results. I will directly post the code for your reference:

Css:

 

Html:

Javascript:

Window. onload = function () {drag ("pic", "box"); function drag (obj, parentNode) {var obj = document. getElementById (obj); if (arguments. length = 1) {var parentNode = window. self; var pWidth = parentNode. innerWidth, pHeight = parentNode. innerHeight;} else {var parentNode = document. getElementById (parentNode); var pWidth = parentNode. offsetWidth, pHeight = parentNode. offsetHeight;} obj. onmousedown = funct Ion (ev) {var ev = ev | event; var disX = ev. clientX-this. offsetLeft, disY = ev. clientY-this. offsetTop; var oWidth = obj. offsetWidth, oHeight = obj. offsetHeight; // prevents the bubble time ev. stopPropagation? Ev. stopPropagation (): ev. cancelBubble = true; document. onmousemove = function (ev) {var ev = ev | event; obj. style. left = ev. clientX-disX + 'px '; obj. style. top = ev. clientY-disY + 'px '; // left if (obj. offsetLeft <= 0) {obj. style. left = 0 ;}; // if (obj. offsetLeft> = pWidth-oWidth) {obj. style. left = pWidth-oWidth + 'px ';}; // The above if (obj. offsetTop <= 0) {obj. style. top = 0 ;}; // The following if (obj. offsetTop> = pHeight-oHeight) {obj. style. top = pHeight-oHeight + 'px ';};}; document. onmouseup = function (ev) {var ev = ev | event; document. onmousemove = document. onmouseup = null ;};}}}

The effect is completely the encapsulated code block, which is quite convenient to reference. Someone will ask, you can use the id to get the DOM element. A page can only be used once, if the page is used for multiple times, it makes sense. If there is one solution, you can name different IDs without breaking the law. solution 2: Change the id to the class, however, it should be noted that getElementsByClassName is the set of classes to be obtained and needs to be rewritten. I will not write it here. If you are interested, rewrite it on your own. Well, it's really over here!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.