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>

  • 相关阅读:
    7、猜年龄
    6、continue语句
    5、break语句
    4、while循环练习
    poj 2378
    poj 2342
    poj 2287
    poj 2228
    poj 1191
    srm 578 dv2 1000pt
  • 原文地址:https://www.cnblogs.com/liuys635/p/12420449.html
Copyright © 2011-2022 走看看