


JavaScript implements the drag-and-drop effect in PC web pages_javascript skills
A few years ago, I participated in the design and development of a real estate website project. I was responsible for the front-end work. Since the project manager has relatively high requirements, I referred to many excellent features of real estate websites and wanted to collect other people’s excellent designs and ideas. When we got together, the design draft and function implementation at that time were simply changed again and again. A good effect achieved today may have to be pushed back to the next day. Forget it, let’s not talk about this. Let’s talk about it. Let’s talk about the case we are going to explain today. I don’t know if you have visited Soufun.com (it is not suspected of advertising at all. Can Soufun pay some advertising fees?), there is one function that the product manager particularly likes, that is, the following This:
This is the current effect, maybe some changes. The original effect is that the picture inside can be dragged up, down, left, and right, and then the building number displayed on the house also moves with the picture. At that time, js The ability was not good enough, and the project manager's requirements were not achieved, but later the project manager rejected this effect and replaced it with another effect
Although the project manager didn’t want this effect, it left a knot in my heart at that time, and I can’t forget it to this day.
Okay, this is my original intention of writing this blog today. I hope it can provide an idea for students who want to achieve this kind of drag effect, but don’t know how to achieve it, so as not to leave any regrets for their youth. Of course, there are many ways to implement drag and drop. Here I will only introduce one method in JavaScript, and slowly understand the principle!
Okay, the jokes are over, let’s get down to business. We must first understand what drag is. You know it, and I know it, but I still want to describe it:
Drag and drop is a container. You can use the mouse to drag it around on the page. Nonsense, the precise description should be, move the mouse to the container, then press the mouse, be careful not to release it, and then drag The mouse and the container can follow the mouse. When you release the mouse, the container will stop there. A real-life example is that there is a box on the table. I put my hand on the box and then move the box. When my hand stops, the box stops. Take it away, the box won’t move, hehe, I understand!
Don’t think that the above is a lot of nonsense, we can get a lot of information from it, the summary is as follows:
Drag = mouse down + mouse movement + mouse up
This completes a drag and drop task. Well, it turns out that this is the principle of drag and drop. If you want to implement drag and drop, you can naturally implement the above three actions to simulate the drag and drop effect. Well, it corresponds to the syntax in JavaScript. Just need to implement these 3 actions:
onmousedown, onmousemove, onmouseup
The implemented code should be:
obj.onmousedown = function(ev){ obj.onmousemove = function(ev){ } ; obj.onmouseup = function(ev){ }; }
Why should the next two actions be written in it? Let’s think about it carefully. Okay, the general idea of the first step is there. The next step is to consider how to make the object move with the mouse. The idea is probably like this:
First of all, the object needs to be positioned, because we need to manipulate its left and top values to make it move. Then we have to consider the mouse. The mouse displacement itself will have a distance. If we know that the mouse has moved How far away is it? Then give this distance to the object. Does the object move the same distance as the mouse? Doesn't this realize dragging? Haha, I have a little bit of ideas, and it feels cute~ The problem now is how to get the distance of the mouse. If you need to know more, please review the box model. I won’t go into it here. Many masters also have related blogs. I use one. Here’s a picture to show it:
Explanation: The blue box is the width and height of the screen, the thick black box is the width and height of the browser's visible area (browser reduction effect), the thin black box is the object to be dragged by the mouse, as shown in the figure, get the coordinates of the mouse , you can use event.clientX, event.clientY to get it, oh;
The general principle of calculation can be referred to the figure below:
Explanation: The left is the initial position, the right is the target position, the origin is the mouse position, the big black box is the visible width of the browser, the small black box is the drag object, see the status of the drag object to the target position, and get the mouse The final position of the mouse, then subtract the difference between the mouse and the object, and then assign it to the top and left values of the object. You can also get the position difference of the mouse, and then add the difference to the initial top and left values. We use the first The second kind is also possible, 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; }; }
这里说明一下:onmousemove和onmouseup之所以用document对象而不用obj对象,是因为如果用obj对象,鼠标在obj内部还好,如果在obj外面的话,拖拽会很怪异,你也可以改成obj体会一下,最后我们在鼠标弹起的时候将事件都清空;
上面的基本拖拽就算完成了,但是细心的同学一定会问,如果页面上有文字的话,拖拽物体会将文字选中,这效果岂不是怪怪的,没错,这是因为拖拽的时候触发了浏览器的默认选择事件,所以,在拖拽的时候,我们要清除这个默认事件,那怎么清除呢?
下面给一个兼容性写法:
if(ev.stopPropagation){ ev.stopPropagation(); }else{ ev.cancelBubble = true; //兼容IE } //简写成 ev.stopPropagation ? ev.stopPropagation() : ev.cancelBubble = true;
将上面的代码放在onmousedown下,鼠标按下就清除浏览器默认事件,文字就不会被选中了,好了,一个简单的拖拽效果就完成了,当然你现在是看不到效果,之所以不给demo链接是为了让你自己试着写一写,这样印象更深刻,
好了,那问题又来了,到这里就这样完了吗?。。。。。。按本人的风格,当然没有,干货还在后面!
如果我想实现这样一个效果,就是这一个大的容器里面(可以是box,也可以是document),怎么样能让我们的拖拽对象不跑出去呢,换句话说,拖到边缘就拖不动了,耶,是不是很多人想要实现的效果,哈哈,我们看看实现的原理是什么:
现实生活中,一个物体在一个盒子里跑不出去,是因为有堵墙,那我们只要能模拟出这堵墙,就可以把物体框起来,那这堵墙要怎么做呢?我们可以换个思路,当拖拽对象拖到边缘的时候,比如说拖到右边,我们将它的left固定住,是不是就不能再往右了,因为left值不能再加了,那么拖到底部,同理我们将top值固定住,就不能再往下拖了,理解吗?
最终的结果就是如下:
//左侧 if(obj.offsetLeft <=0){ obj.style.left = 0; }; //右侧 if(obj.offsetLeft >= pWidth - oWidth){ obj.style.left = pWidth - oWidth + 'px'; }; //上面 if(obj.offsetTop <= 0){ obj.style.top = 0; }; //下面 if(obj.offsetTop >= pHeight - oHeight){ obj.style.top = pHeight - oHeight + 'px'; };
说明:pWidth,pHeight 表示父级元素的宽高(这里是表示相对于父级的宽高限制),oWidth,oHeigt表示拖拽元素的宽高
最后,我将整个拖拽代码整理了一下:
/* 参数说明: 元素绝对定位,父级相对定位,如果父级为window,则可以不用 传一个参数,表示父级为window,物体相对于window范围拖动 传2个参数,则父级为第二个参数,物体相对于父级范围拖动 参数为id值 */ 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 = function(ev){ var ev = ev || event; var disX = ev.clientX - this.offsetLeft,disY = ev.clientY - this.offsetTop; var oWidth = obj.offsetWidth,oHeight = obj.offsetHeight; //阻止冒泡时间 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'; //左侧 if(obj.offsetLeft <=0){ obj.style.left = 0; }; //右侧 if(obj.offsetLeft >= pWidth - oWidth){ obj.style.left = pWidth - oWidth + 'px'; }; //上面 if(obj.offsetTop <= 0){ obj.style.top = 0; }; //下面 if(obj.offsetTop >= pHeight - oHeight){ obj.style.top = pHeight - oHeight + 'px'; }; }; document.onmouseup = function(ev){ var ev = ev || event; document.onmousemove = document.onmouseup = null; }; } }
说明:我这里处理的效果是,如果传一个参数,表示相对的对象是window对象,如果传2个参数,第一个是拖拽对象,第二个为相对父级
开篇就说了,搜房网的那个图片拖拽效果是我的一个心结,我写了一个类似的效果,供大家参考,因为自己没有买服务器,所以效果我就不展示了,直接把代码贴出来,供大家参考:
css:
<style> .box{ width:600px; height:400px; margin:50px auto; position:relative; overflow:hidden; } #box{ width:1000px; height:800px; position:absolute; left:50%; top:50%; margin:-400px 0 0 -500px; } #pic{ width:800px; height:600px; background:url(images/pic1.jpg) no-repeat; position:absolute; left:100px; top:100px; } #pic:hover{ cursor:move; } </style>
html:
<div class="box"> <div id="box"> <div id="pic"></div> </div> </div>
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 = function(ev){ var ev = ev || event; var disX = ev.clientX - this.offsetLeft,disY = ev.clientY - this.offsetTop; var oWidth = obj.offsetWidth,oHeight = obj.offsetHeight; //阻止冒泡时间 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'; //左侧 if(obj.offsetLeft <=0){ obj.style.left = 0; }; //右侧 if(obj.offsetLeft >= pWidth - oWidth){ obj.style.left = pWidth - oWidth + 'px'; }; //上面 if(obj.offsetTop <= 0){ obj.style.top = 0; }; //下面 if(obj.offsetTop >= pHeight - oHeight){ obj.style.top = pHeight - oHeight + 'px'; }; }; document.onmouseup = function(ev){ var ev = ev || event; document.onmousemove = document.onmouseup = null; }; } } }
效果完全是用的那个封装代码块,引用起来也挺方便,有人会问了,你这用的id获取DOM元素,一个页面只能用一次啊,如果页面多次使用呢,有道理,解决方案之一,那就命名不同的id呗,又不犯法,方案二,获取id的地方改成获取class,但是要注意的是,getElementsByClassName是获取的class集合,需要改写一下,这里我就不写了,有兴趣的同学自行改写一下,好了,到这里真的结束了!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

If you encounter the error "The access point is temporarily full" when connecting to a Wi-Fi router or mobile hotspot on your Windows 11/10 PC, this is usually caused by network overload or too many connected devices. In order to solve this problem and successfully connect to the Internet, you can try the following methods: 1. Wait for a while for other devices to disconnect before trying to connect again. 2. Restart your Wi-Fi router or mobile hotspot to clear the network cache and reassign the IP address. 3. Make sure your PC’s Wi-Fi adapter driver is up to date, check for updates through Device Manager. 4. Try to connect at different times. Avoiding peak hours may have better connection opportunities. 5. Consider adding AccessP
![Windows PC keeps booting into BIOS [Fix]](https://img.php.cn/upload/article/000/887/227/171012121854600.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
If your Windows PC frequently enters the BIOS interface, this may cause difficulty in use. I'm stuck with the BIOS screen every time I turn on my computer, and restarting doesn't help. If you are facing this problem, then the solutions provided in this article will help you. Why does my computer keep booting in BIOS? Your computer's frequent restarts in BIOS mode may be caused by a variety of reasons, such as improper boot sequence settings, damaged SATA cables, loose connections, BIOS configuration errors, or hard drive failures, etc. Fix Windows PC Keeps Booting into BIOS If your Windows PC keeps booting into BIOS, use the fix below. Check your boot order and re-plug the

SamsungFlow is a convenient and practical tool that allows you to easily connect your Galaxy phone to your Windows PC. With SamsungFlow, you can conveniently share content between devices, sync notifications, mirror smartphones, and more. This article will introduce how to use SamsungFlow on a Windows computer. How to use Smartphone Streaming on Windows PC To use SamsungFlow to connect your Windows PC and Galaxy Phone, you need to ensure that your Galaxy smartphones and tablets are running Android 7.0 or higher, and your Windows PC is running Windows 10 or higher.

This article will teach you how to download all OneDrive files to your PC at once. OneDrive is a powerful cloud storage platform that allows users to access their files anytime, anywhere. Sometimes, users may need to back up files locally or access them offline. Read on to learn how to do this easily. How to download all OneDrive files to PC at once? Follow these steps to download all OneDrive files to your Windows PC at once: Launch Onedrive and navigate to My Files. All files uploaded on OneDrive will be available here. Press CTRL+A to select all files, or check the checkbox to toggle selection of all items. Click on the download option at the top,

Speaking of which, we have already produced many issues of the foreign junk series, but before that, most of them were mobile phones and assembled PCs. The former has average playability, while the latter is full of uncertainty. For example, the computer we spent 300 to install last time has now entered a state of non-stop driver removal. However, "picking up rags" is what it is, and the coexistence of risks and benefits is the norm. For example, I "picked up" the ASUS ChromeBox this time. I originally wanted to make it into a Macmini (fake), but I encountered many unexpected problems during the process and failed to achieve the intended goal. In the end, I had to settle for the next best thing and choose to flash Windows on it. Although the attempt to blacken apples fell to the last step, I had a lot of fun in the whole process. And as

If 2023 is recognized as the first year of AI, then 2024 is likely to be a key year for the popularization of large AI models. In the past year, a large number of large AI models and a large number of AI applications have emerged. Manufacturers such as Meta and Google have also begun to launch their own online/local large models to the public, similar to "AI artificial intelligence" that is out of reach. The concept suddenly came to people. Nowadays, people are increasingly exposed to artificial intelligence in their lives. If you look carefully, you will find that almost all of the various AI applications you have access to are deployed on the "cloud". If you want to build a device that can run large models locally, then the hardware is a brand-new AIPC priced at more than 5,000 yuan. For ordinary people,

"Operation Delta" will launch a large-scale PC test called "Codename: ZERO" today (March 7). Last weekend, this game held an offline flash mob experience event in Shanghai, and 17173 was also fortunate to be invited to participate. This test is only more than four months away from the last time, which makes us curious, what new highlights and surprises will "Operation Delta" bring in such a short period of time? More than four months ago, I experienced "Operation Delta" in an offline tasting session and the first beta version. At that time, the game only opened the "Dangerous Action" mode. However, Operation Delta was already impressive for its time. In the context of major manufacturers flocking to the mobile game market, such an FPS that is comparable to international standards

The Chinese style hardcore martial arts action game "Yi Wen Lu: Samsara" starts online trial play today. This is a multi-platform hard-core martial arts action stand-alone game that incorporates traditional Chinese cultural elements. In the game, players play a martial arts character who prevents world disaster and restores stability and peace. Officials claim that players can explain the value of martial arts culture through exquisite art scenes and vivid stories, explore and display the connotation and spirit of martial arts culture, and experience a wonderful journey at the same time. According to the developer, the team’s original design intention was to allow players to better experience the elegance of martial arts. The team studied most of the various schools and techniques of Chinese martial arts and presented them realistically in the game. Players can learn or encounter enemies using a variety of skills and moves, such as Tai Chi, sword skills, and
