search
HomeWeb Front-endJS TutorialJavaScript method to implement DIV layer dragging and dynamically add new layers_javascript skills

The example in this article describes how to implement DIV layer dragging and dynamically adding new layers using JavaScript. Share it with everyone for your reference. The specific analysis is as follows:

Add a new DIV layer without refreshing, and drag the layer. Drag the layer with the mouse to move the position. Save the JS part as a new file. When used, import it from the outside. This drag Layer code is very popular, and this effect can often be seen on large websites such as GG and YAHOO.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DIV层拖动,动态增加新层的JavaScript</title>
<style>
body {margin:0px;padding:0px;font-size:12px;text-align:center;}
body > div {text-align:center; margin-right:auto; margin-left:auto;} 
.content{width:900px;}
.content .left{
  float:left;
  width:20%;
  border:1px solid #0066CC;
  margin:3px;
}
.content .center{
 float:left;
 border:1px solid #FF0000;
 margin:3px;
 width:57%
}
.content .right{
 float:right;
 width:20%;
 border:1px solid #FF0000;
 margin:3px
}
.mo{
 height:auto;
 border:1px solid #CCC;
 margin:3px;
 background:#FFF
}
.mo h1{
 background:#ECF9FF;
 height:18px;
 padding:3px;
 cursor:move
}
.closediv{
 cursor:default;
}
.minusspan{
 cursor:default;
}
.mo .nr{
 height:80px;
 border:1px solid #F3F3F3;
 margin:2px
}
h1{
 margin:0px;
 padding:0px;
 text-align:left;
 font-size:12px
}
.dragging {
  FILTER: progid:DXImageTransform.Microsoft.Alpha(opacity=60);
 opacity: 0.6;
 moz-opacity: 0.6
}
</style>
<script language="javascript">
var dragobj={}
window.onerror=function(){return false}
var domid=12
function on_ini(){
  String.prototype.inc=function(s){return this.indexOf(s)>-1&#63;true:false}
  var agent=navigator.userAgent
  window.isOpr=agent.inc("Opera")
  window.isIE=agent.inc("IE") && !isOpr
  window.isMoz=agent.inc("Mozilla") && !isOpr && !isIE
  if(isMoz){
    Event.prototype.__defineGetter__("x",function(){return this.clientX+2})
    Event.prototype.__defineGetter__("y",function(){return this.clientY+2})
  }
  basic_ini()
}
function basic_ini(){
  window.$=function(obj){return typeof(obj)=="string"&#63;document.getElementById(obj):obj}
  window.oDel=function(obj){if($(obj)!=null){$(obj).parentNode.removeChild($(obj))}}
}
window.oDel=function(obj){if($(obj)!=null){$(obj).parentNode.removeChild($(obj))}}
window.onload=function(){
  on_ini()
  var o=document.getElementsByTagName("h1")
  for(var i=0;i<o.length;i++){
    o[i].onmousedown=addevent;
    //添加折叠和关闭按钮
    var tt = document.createElement("div");
    tt.style.cssText = "float:left";
    
    var span = document.createElement("span");
    span.innerHTML = "--"+o[i].innerHTML;
    span.style.cssText = "cursor:default;";
    span.onmousedown = minusDiv;
    tt.appendChild(span);
    
    var close = document.createElement("div");
    close.innerHTML = "X";
    close.style.cssText = "cursor:default;float:right";
    close.onmousedown = closeDiv;
    o[i].innerHTML = "";
    o[i].appendChild(tt);
    o[i].appendChild(close);
  }
}
//折叠或者显示层
function minusDiv(e)
{
  e=e||event
  var nr = this.parentNode.parentNode.nextSibling; //取得内容层
  nr.style.display = nr.style.display==""&#63;"none":"";
}
//移出层
function closeDiv(e)
{
  e=e||event
  var mdiv = this.parentNode.parentNode; //取得目标层
  oDel(mdiv);
}
function addevent(e){
  if(dragobj.o!=null)
    return false
  e=e||event
  dragobj.o=this.parentNode
  dragobj.xy=getxy(dragobj.o)
  dragobj.xx=new Array((e.x-dragobj.xy[1]),(e.y-dragobj.xy[0]))
  //dragobj.o.className = 'dragging';
  dragobj.o.style.width=dragobj.xy[2]+"px"
  dragobj.o.style.height=dragobj.xy[3]+"px"
  dragobj.o.style.left=(e.x-dragobj.xx[0])+"px"
  dragobj.o.style.top=(e.y-dragobj.xx[1])+"px"
  dragobj.o.style.position="absolute"
  dragobj.o.style.filter='alpha(opacity=60)'; //添加拖动透明效果
  var om=document.createElement("div")
  dragobj.otemp=om
  om.style.width=dragobj.xy[2]+"px"
  om.style.height=dragobj.xy[3]+"px"
  om.style.border = "1px dashed red"; //ikaiser添加,实现虚线框
  dragobj.o.parentNode.insertBefore(om,dragobj.o)
  return false
}
document.onselectstart=function(){return false}
window.onfocus=function(){document.onmouseup()}
window.onblur=function(){document.onmouseup()}
document.onmouseup=function(){
  if(dragobj.o!=null){
    dragobj.o.style.width="auto"
    dragobj.o.style.height="auto"
    dragobj.otemp.parentNode.insertBefore(dragobj.o,dragobj.otemp)
    dragobj.o.style.position=""
    oDel(dragobj.otemp)
    dragobj={}
  }
}
document.onmousemove=function(e){
  e=e||event
  if(dragobj.o!=null){
    dragobj.o.style.left=(e.x-dragobj.xx[0])+"px"
    dragobj.o.style.top=(e.y-dragobj.xx[1])+"px"
    createtmpl(e, dragobj.o) //传递当前拖动对象
  }
}
function getxy(e){
  var a=new Array()
  var t=e.offsetTop;
  var l=e.offsetLeft;
  var w=e.offsetWidth;
  var h=e.offsetHeight;
  while(e=e.offsetParent){
    t+=e.offsetTop;
    l+=e.offsetLeft;
  }
  a[0]=t;a[1]=l;a[2]=w;a[3]=h
 return a;
}
function inner(o,e){
  var a=getxy(o)
  if(e.x>a[1] && e.x<(a[1]+a[2]) && e.y>a[0] && e.y<(a[0]+a[3])){
    if(e.y<(a[0]+a[3]/2))
      return 1;
    else
      return 2;
  }else
    return 0;
}
//将当前拖动层在拖动时可变化大小,预览效果
function createtmpl(e, elm){
  for(var i=0;i<domid;i++){
    if(document.getElementById("m"+i) == null) //已经移出的层不再遍历
      continue;
    if($("m"+i)==dragobj.o)
      continue
    var b=inner($("m"+i),e)
    if(b==0)
      continue
    dragobj.otemp.style.width=$("m"+i).offsetWidth
    elm.style.width = $("m"+i).offsetWidth;
    //1为下移,2为上移
    if(b==1){
      $("m"+i).parentNode.insertBefore(dragobj.otemp,$("m"+i))
    }else{
      if($("m"+i).nextSibling==null){
        $("m"+i).parentNode.appendChild(dragobj.otemp)
      }else{
        $("m"+i).parentNode.insertBefore(dragobj.otemp,$("m"+i).nextSibling)
      }
    }
    return
  }
  for(var j=0;j<3;j++){
    if($("dom"+j).innerHTML.inc("div")||$("dom"+j).innerHTML.inc("DIV"))
      continue
    var op=getxy($("dom"+j))
    if(e.x>(op[1]+10) && e.x<(op[1]+op[2]-10)){
      $("dom"+j).appendChild(dragobj.otemp)
      dragobj.otemp.style.width=(op[2]-10)+"px"
    }
  }
}
function add_div()
{
  var o=document.createElement("div")
  o.className="mo"
  o.id="m"+domid
  $('dom0').appendChild(o)
  o.innerHTML="<h1 id="dom-domid">dom"+domid+"</h1><div class=nr></div>"
  o.getElementsByTagName("h1")[0].onmousedown=addevent
  domid++
}
</script>
</head>
<body>
<INPUT TYPE="button" value="添加一个新的DIV层" onclick="add_div();">
<div class=content>
  <div class=left id=dom0>
    <div class=mo id=m0>
      <h1 id="dom">dom0</h1>
      <div class="nr"></div>
    </div>
    <div class=mo id=m1>
      <h1 id="dom">dom1</h1><div class="nr"></div>
    </div>
    <div class=mo id=m2><h1 id="dom">dom2</h1><div class="nr"></div></div>
    <div class=mo id=m3><h1 id="dom">dom3</h1><div class="nr"></div></div>
  </div>
  <div class=center id=dom1>
    <div class=mo id=m4><h1 id="dom">dom4</h1><div class="nr"></div></div>
    <div class=mo id=m5><h1 id="dom">dom5</h1><div class="nr"></div></div>
  </div>
  <div class=right id=dom2>
    <div class=mo id=m8><h1 id="dom">dom8</h1><div class="nr"></div></div>
    <div class=mo id=m9><h1 id="dom">dom9</h1><div class="nr"></div></div>
  </div>
</div>
</body>
</html>

I hope this article will be helpful to everyone’s JavaScript programming design.

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
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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

Video Face Swap

Video Face Swap

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

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.