search
HomeWeb Front-endJS TutorialHow to drag and drop using javascript_javascript skills

Javascript is characterized by DOM processing and webpage effects. In most cases, we only use the simplest functions of this language, such as making image carousels/webpage tabs, etc. This article will teach you Show how to create drag and drop on your own web page.

There are many reasons to add drag-and-drop functionality to your website, the simplest one is data reorganization. For example: you have a sequence of contents for the user to sort. The user needs to enter each item or select it with select. The alternative to the previous method is drag and drop. Maybe your website also needs a navigation window that users can drag! Well these effects are very simple: because you can achieve them easily!

It is actually not very complicated to implement drag and drop on the web page. First, you need to know the mouse coordinates. Second, you need to know that the user clicks on a web page element and drags it. Finally, we need to move this element.

<SCRIPT 
      src="http://www.blueidea.com/articleimg/2006/07/3791/drag_drop.js" 
      type=text/javascript></SCRIPT>
<STYLE type=text/css>LI {
 MARGIN-BOTTOM: 10px
}
OL {
 MARGIN-TOP: 5px
}
.DragContainer {
 BORDER-RIGHT: #669999 2px solid; PADDING-RIGHT: 5px; BORDER-TOP: #669999 2px solid; PADDING-LEFT: 5px; FLOAT: left; PADDING-BOTTOM: 0px; MARGIN: 3px; BORDER-LEFT: #669999 2px solid; WIDTH: 100px; PADDING-TOP: 5px; BORDER-BOTTOM: #669999 2px solid
}
.OverDragContainer {
 BORDER-RIGHT: #669999 2px solid; PADDING-RIGHT: 5px; BORDER-TOP: #669999 2px solid; PADDING-LEFT: 5px; FLOAT: left; PADDING-BOTTOM: 0px; MARGIN: 3px; BORDER-LEFT: #669999 2px solid; WIDTH: 100px; PADDING-TOP: 5px; BORDER-BOTTOM: #669999 2px solid
}
.OverDragContainer {
 BACKGROUND-COLOR: #eee
}
.DragBox {
 BORDER-RIGHT: #000 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: #000 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 10px; MARGIN-BOTTOM: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #000 1px solid; WIDTH: 94px; CURSOR: pointer; PADDING-TOP: 2px; BORDER-BOTTOM: #000 1px solid; FONT-FAMILY: verdana, tahoma, arial; BACKGROUND-COLOR: #eee
}
.OverDragBox {
 BORDER-RIGHT: #000 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: #000 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 10px; MARGIN-BOTTOM: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #000 1px solid; WIDTH: 94px; CURSOR: pointer; PADDING-TOP: 2px; BORDER-BOTTOM: #000 1px solid; FONT-FAMILY: verdana, tahoma, arial; BACKGROUND-COLOR: #eee
}
.DragDragBox {
 BORDER-RIGHT: #000 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: #000 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 10px; MARGIN-BOTTOM: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #000 1px solid; WIDTH: 94px; CURSOR: pointer; PADDING-TOP: 2px; BORDER-BOTTOM: #000 1px solid; FONT-FAMILY: verdana, tahoma, arial; BACKGROUND-COLOR: #eee
}
.miniDragBox {
 BORDER-RIGHT: #000 1px solid; PADDING-RIGHT: 2px; BORDER-TOP: #000 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 10px; MARGIN-BOTTOM: 5px; PADDING-BOTTOM: 2px; BORDER-LEFT: #000 1px solid; WIDTH: 94px; CURSOR: pointer; PADDING-TOP: 2px; BORDER-BOTTOM: #000 1px solid; FONT-FAMILY: verdana, tahoma, arial; BACKGROUND-COLOR: #eee
}
.OverDragBox {
 BACKGROUND-COLOR: #ffff99
}
.DragDragBox {
 BACKGROUND-COLOR: #ffff99
}
.DragDragBox {
 FILTER: alpha(opacity=50); BACKGROUND-COLOR: #ff99cc
}
LEGEND {
 FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: #666699; FONT-FAMILY: verdana, tahoma, arial
}
FIELDSET {
 PADDING-RIGHT: 3px; PADDING-LEFT: 3px; PADDING-BOTTOM: 3px; PADDING-TOP: 3px
}
.History {
 FONT-SIZE: 10px; OVERFLOW: auto; WIDTH: 100%; FONT-FAMILY: verdana, tahoma, arial; HEIGHT: 82px
}
#DragContainer8 {
 BORDER-RIGHT: #669999 1px solid; PADDING-RIGHT: 0px; BORDER-TOP: #669999 1px solid; PADDING-LEFT: 5px; PADDING-BOTTOM: 0px; BORDER-LEFT: #669999 1px solid; WIDTH: 110px; PADDING-TOP: 5px; BORDER-BOTTOM: #669999 1px solid; HEIGHT: 110px
}
.miniDragBox {
 FLOAT: left; MARGIN: 0px 5px 5px 0px; WIDTH: 20px; HEIGHT: 20px
}
PRE {
 BORDER-RIGHT: #ccc 1px solid; PADDING-RIGHT: 10px; BORDER-TOP: #ccc 1px solid; PADDING-LEFT: 10px; PADDING-BOTTOM: 10px; BORDER-LEFT: #ccc 1px solid; PADDING-TOP: 10px; BORDER-BOTTOM: #ccc 1px solid; BACKGROUND-COLOR: #f8f8f0
}
</STYLE>
<body>
<FIELDSET id=Demo4><LEGEND>样例- 拖拽页面元素</LEGEND>
      <DIV>
      <DIV class=DragContainer id=DragContainer4 overclass="OverDragContainer">
      <DIV class=DragBox id=Item1 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #1</DIV>
      <DIV class=DragBox id=Item2 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #2</DIV>
      <DIV class=DragBox id=Item3 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #3</DIV>
      <DIV class=DragBox id=Item4 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #4</DIV></DIV>
      <DIV class=DragContainer id=DragContainer5 overclass="OverDragContainer">
      <DIV class=DragBox id=Item5 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #5</DIV>
      <DIV class=DragBox id=Item6 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #6</DIV>
      <DIV class=DragBox id=Item7 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #7</DIV>
      <DIV class=DragBox id=Item8 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #8</DIV></DIV>
      <DIV class=DragContainer id=DragContainer6 overclass="OverDragContainer">
      <DIV class=DragBox id=Item9 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #9</DIV>
      <DIV class=DragBox id=Item10 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #10</DIV>
      <DIV class=DragBox id=Item11 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #11</DIV>
      <DIV class=DragBox id=Item12 overclass="OverDragBox" 
      dragclass="DragDragBox">Item #12</DIV></DIV></DIV></FIELDSET>
</body>
</html>

Get mouse movement information

First we need to get the coordinates of the mouse. We just add a user function to document.onmousemove:

document.onmousemove = mouseMove;

function mouseMove(ev){
 ev           = ev || window.event;
 var 
mousePos = mouseCoords(ev);
}
function mouseCoords(ev){
 if(ev.pageX || ev.pageY){
  return 
{x:ev.pageX, y:ev.pageY};
 }
 return {
  x:ev.clientX + 
document.body.scrollLeft - document.body.clientLeft,
  y:ev.clientY + 
document.body.scrollTop  - document.body.clientTop
 };
}
<script> 

function mouseMove(ev){ 
    ev           = ev || window.event; 
    var mousePos = mouseCoords(ev); 
        document.getElementById(&#39;xxx&#39;).value = mousePos.x; 
        document.getElementById(&#39;yyy&#39;).value = mousePos.y; 
} 

function mouseCoords(ev){ 
    if(ev.pageX || ev.pageY){ 
        return {x:ev.pageX, y:ev.pageY}; 
    } 
    return { 
        x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, 
        y:ev.clientY + document.body.scrollTop  - document.body.clientTop 
    }; 
} 

document.onmousemove = mouseMove; 
</script>Mouse X Position: 
<input id=xxx type=text> 

Mouse Y Position: 
<input id=yyy type=text> 

</body> 
</html>

You must first declare an evnet object. Whenever you move the mouse/click/press a button, etc., there will be an event corresponding to it. In Internet Explorer, event is a global variable and will be stored in window.event. In Firefox, or other browsers, the event event will be obtained by the corresponding custom function. When we assign the mouseMove function to document.onmousemove, mouseMove will obtain the mouse movement event.​

(ev = ev || window.event) This allows ev to obtain the event event in all browsers. Under Firefox, "||window.event" will not work because ev already has a value assigned . Under MSIE ev is empty, so ev will be set to window.event.

Because we need to obtain mouse coordinates multiple times in this article, we designed the mouseCoords function, which only contains one parameter, the event.

We need to run under other browsers including MSIE and Firefox. Firefox uses event.pageX and event.pageY to represent the position of the mouse corresponding to the upper left corner of the document. If you have a 500*500 window and your mouse is in the middle, then paegX and pageY will be 250. When you scroll the page down 500px, then pageY will be 750. At this time, pageX remains unchanged, still 250.

MSIE is the opposite of this. MSIE uses event.clientX and event.clientY to represent the position of the mouse and the ie window, not the document. When we have a 500*500 window and the mouse is in the middle, then clientX and clientY are also 250. If you scroll the window vertically to any position, clientY is still 250, because the relative ie window has not changed. To get correct results, we must add scrollLeft and scrollTop properties that are relative to the mouse position of the document. Finally, since MSIE does not have a document starting position of 0,0, a 2px border is usually set around it. The width of the border is included in the two properties of document.body.clientLeft and clientTop. We then add these to the mouse In position.

Fortunately, the mouseCoords function is completed and we no longer have to worry about coordinates.

Capture mouse clicks

Next time we will know when the mouse is clicked and when it is released. If we skip this step, we'll never know what the mouse does when we drag, which would be annoying and counterintuitive.

Here are two functions to help us: onmousedown and onmouseup. We pre-set the function to receive document.onmousemove, so it looks like we will get document.onmousedown and document.onmouseup. But when we get document.onmousedown, we also get the click properties of any object such as: text, images, tables, etc. We only want to get those properties that need to be dragged, so we set up a function to get the objects we need to move. .

<base href=&#39;http://www.blueidea.com&#39;>
<script> 
function mouseDown(ev){ 
    ev         = ev || window.event; 
    var target = ev.target || ev.srcElement; 

    if(target.onmousedown || target.getAttribute(&#39;DragObj&#39;)){ 
        return false; 
    } 
} 

function makeClickable(item){ 
    if(!item) return; 
    item.onmousedown = function(ev){ 
        document.getElementById(&#39;ClickImage&#39;).value = this.name; 
    } 
} 
document.onmousedown = mouseDown; 
window.onload = function(){ 
    makeClickable(document.getElementById(&#39;ClickImage1&#39;)); 
    makeClickable(document.getElementById(&#39;ClickImage2&#39;)); 
    makeClickable(document.getElementById(&#39;ClickImage3&#39;)); 
    makeClickable(document.getElementById(&#39;ClickImage4&#39;)); 
}</script> 

<FIELDSET id=Demo3> 
<h3> 
  Demo - Click any image 
</h3> 
<img src="/static/imghwm/default1.png"  data-src="/articleimg/2006/07/3791/drag_drop_spade.gif"  class="lazy"  id=ClickImage1    
name=Spade><img src="/static/imghwm/default1.png"  data-src="/articleimg/2006/07/3791/drag_drop_heart.gif"  class="lazy"  id=ClickImage2    
name=Heart><img src="/static/imghwm/default1.png"  data-src="/articleimg/2006/07/3791/drag_drop_diamond.gif"  class="lazy"  id=ClickImage3    
name=Diamond><img src="/static/imghwm/default1.png"  data-src="/articleimg/2006/07/3791/drag_drop_club.gif"  class="lazy"  id=ClickImage4   
 name=Club>  

You clicked on: <INPUT id=ClickImage type="text"> </FIELDSET>

Move an element

We know how to capture mouse movements and clicks. All that's left is to move the element. First of all, to determine a clear page position, the CSS style sheet must use 'absolute'. Setting the absolute position of the element means that we can use the .top and .left of the style sheet to position it, and we can use the relative position to position it. We move the mouse relative to the top-left of the page. Based on this, we can proceed to the next step.

When we define item.style.position='absolute', all operations are to change the left coordinate and top coordinate, and then it moves.


document.onmousemove = mouseMove;
document.onmouseup = mouseUp;

var dragObject = null;
var mouseOffset = null;

function getMouseOffset(target, ev){
ev = ev || window.event;

var docPos = getPosition(target);
var mousePos = mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e){
var left = 0;
var top = 0;

while (e.offsetParent){
left = e.offsetLeft;
top = e.offsetTop;
e = e.offsetParent;
}

 left = e.offsetLeft;
 top  = e.offsetTop;

 return {x:left, y:top};
}

function mouseMove(ev){
 ev           = ev || window.event;
 var mousePos = mouseCoords(ev);

 if(dragObject){
  dragObject.style.position = 'absolute';
  dragObject.style.top      = mousePos.y - mouseOffset.y;
  dragObject.style.left     = mousePos.x - mouseOffset.x;

  return false;
 }
}
function mouseUp(){
 dragObject = null;
}

function makeDraggable(item){
 if(!item) return;
 item.onmousedown = function(ev){
  dragObject  = this;
  mouseOffset = getMouseOffset(this, ev);
  return false;
 }
}


Statement
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.