Home > Web Front-end > JS Tutorial > js implements drag and drop function

js implements drag and drop function

高洛峰
Release: 2017-03-01 15:48:06
Original
1164 people have browsed it

This article mainly introduces examples of js implementing drag and drop effects, which has a good reference value. Let’s take a look at it with the editor

Rendering: (The red square can be dragged arbitrarily )

js implements drag and drop function

The code is as follows:

 <meta charset="UTF-8">
 <meta name="Generator" content="EditPlus®">
 <meta name="Author" content="">
 <meta name="Keywords" content="">
 <meta name="Description" content="">
 <title>Document</title>
 <style type="text/css">
 *{
 margin:0;
 padding:0;
 }
 body{
 background:url("img/2345_image_file_copy_1.jpg");
 }
 #d1{
 width:100px;
 height:100px;
 background:red;
 margin-left:300px;
 }
 </style>
 </head>
 <body>
 <p id="d1"></p>
 </body>
 <script>
 window.onload=function(){
 var d1=document.getElementById("d1");
 d1.onmousedown=function(e){
 var mouseX=e.clientX;
 var mouseY=e.clientY;//计算xy
 var pianyiX=mouseX-d1.offsetLeft;
 var pianyiY=mouseY-d1.offsetTop;
 document.onmousemove=function(e){
 var newX=e.clientX-pianyiX;
 var newY=e.clientY-pianyiY;
 d1.style.marginLeft=newX+"px";
 d1.style.marginTop=newY+"px";
 }
 };
 document.onmouseup = function(e){
 document.onmousemove = null ;
 };
 }
 /*
 结果,上面的onmousemove要写在document上,我写在p上导致错误
 */
 </script>
</html>
Copy after login

More articles related to js implementation of drag and drop function Please pay attention to PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template