zoukankan      html  css  js  c++  java
  • js实现拖放

    <!DOCTYPE html>
    <html>
    <head>
    <title>a元素拖到b元素里b元素就成了a元素的父元素 </title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!--<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no" />
    <meta name="format-detection"content="telephone=no"/>-->
    <style>
    #div{
    100px;
    height: 100px;
    border-radius: 50%;
    background-color: #ff0000;
    margin: 40px auto 0 auto;
    line-height: 100px;
    text-align: center;
    color: #fff0df;
    }
    #container{
    display: flex;
    }
    #container>div{
    height: 200px;
    200px;
    flex:1;
    border: 1px solid #000000;
    padding-top: 20px;
    text-align: center;
    }
    </style>
    </head>
    <body>
    <div id="container">
    <div>yellow</div>
    <div>green</div>
    <div>blue</div>
    <div>black</div>
    </div>
    <div draggable="true" id="div"></div>
    <script>
    const [div,conatiner]=[
    document.getElementById('div'),
    document.getElementById('container')
    ];
    div.ondragstart=function(e){
    div.innerHTML='dragstart';
    conatiner.style.backgroundColor='rgba(255,0,0,.1)';
    e.dataTransfer.setData('id','div');
    }
    div.ondrag=function(e){
    div.innerHTML='dragging';
    }
    div.ondragend=function(e){
    div.innerHTML='dragend';
    conatiner.style.backgroundColor='rgba(255,0,0,0)';
    }
    conatiner.ondragenter=function(e){
    e.preventDefault();
    e.target.style.backgroundColor='rgba(255,0,0,.3)';
    //drop之前没有获取不到data对象
    div.style.backgroundColor= e.target.innerHTML;
    }
    conatiner.ondragleave=function(e){
    e.preventDefault();
    e.target.style.backgroundColor='rgba(255,0,0,0)';
    }
    //目标对象容许被拖拽元素拖拽进来 默认不容许
    conatiner.ondragover=function(e){
    e.preventDefault();
    }
    //目标对象接受被拖拽元素放下
    conatiner.ondrop=function(e){
    const target=e.target;
    const id=e.dataTransfer.getData('id');
    const div=document.getElementById(id);
    div.style.backgroundColor=target.innerHTML;
    target.appendChild(div);
    }
    </script>
    </body>
    </html>

  • 相关阅读:
    基于范围的for循环
    ML.NET技术研究系列-2聚类算法KMeans
    SQLServer常用运维SQL整理
    ML.NET技术研究系列-1入门篇
    Kafka基本知识整理
    .NetCore技术研究-EntityFramework Core 3.0 Preview
    容器技术研究-Kubernetes基本概念
    特来电混沌工程实践-混沌事件注入
    .Net Core技术研究-Span<T>和ValueTuple<T>
    Visual Studio Git本地Repos和GitHub远程Repos互操作
  • 原文地址:https://www.cnblogs.com/liuys635/p/12420449.html
Copyright © 2011-2022 走看看