【前端教程02】js拖拽布局demo

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
      .page {
         display: flex;
      }

      .box1 input {
         width: 260px;
         height: 50px;
         border: solid 1px blue;
         background-color: #dcdcdc;
         margin-top: 20px;

      }
      .box2{
         width: 260px;
         height: 50px;
         background-color: #dcdcdc;
         color: #333;
         text-align: center;
         line-height: 50px;
      }
      .box3 button{
         width: 260px;
         height: 50px;
         background-color: red;
         color: #fff;
         text-align: center;
         line-height: 50px;
         border: none;
         margin-top: 20px;
      }
      .box4{
         width: 300px;
         height: 600px;
         border: 1px solid blue;
     
      }
   </style>
</head>

<body>
  <div class="page">
   <!-- 可拖拽元素 -->
   <div style="width: 400px;">
      <div draggable="true" class="box1 drage">
         <input type="text" placeholder="请输入">
      </div>
      <div draggable="true" class="box2 drage">
         <h1>这里是文案区域</h1>
      </div>
      <div draggable="true" class="box3 drage">
         <button>提交</button>
      </div>
   </div>
   
   <!-- 布局区域 -->
   <div id="box4" class="box4">拖入布局</div>

  </div>

</body>

<script>
// 拖拽
//  var box1 = document.getElementById('box1')

//  box1.addEventListener('dragstart',function(e){
//  })

//  box3.addEventListener('drag',function(e){
//       box3.style.marginLeft = e.clientX + 'px'
//    box3.style.marginTop = e.clientY + 'px'
//  })

var box4 = document.getElementById('box4')

function setDom(e){
   const x = e.clientX 
   const y = e.clientY 
   // 拖动到指定区域则插入
   if(x < 400 && x > 700 ||  y > 0 && y < 600 ) {
      var dom = document.createElement('div')
      dom.innerHTML = e.toElement.outerHTML
      dom.style.marginLeft = '20px'
      box4.append( dom)
   }
}

var dragArr = document.getElementsByClassName('drage')

// 拖动每个元素箭头拖拽事件
for (let i=0; i<dragArr.length;i++ ) {
   dragArr[i].addEventListener('dragend', function(e) {
      setDom(e)
   })
}

</script>
 
</html>

 

看效果图

posted @   JeckHui  阅读(85)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2022-06-30 【vue开发】富文本编辑器vue-ueditor-wrap
2020-06-30 【vue创建项目】创建一个ts项目包含sass
点击右上角即可分享
微信分享提示