json|js css3实现图片拖拽效果

时间:2021-07-06  来源:css3教程  阅读:

 

 代码如下

 

  

    

    

    

      body{

        text-align: center;

      }

      .container{

        display: flex;

        justify-content: center;

      }

      .colorBox{

        width: 100px;

        height: 100px;

        border:1px solid gray;

        margin: 0 20px;

      }

      .showBox{

        width: 100px;

        height: 100px;

        border:5px dashed gray;

        margin: 0 auto;

      }

      .colorBox:nth-child(1){

        background-color: orange;

      }

      .colorBox:nth-child(2){

        background-color: skyblue;

      }

      .colorBox:nth-child(3){

        background-color: yellowgreen;

      }

      img{

        border: 1px solid gray;

        margin:0 20px;

      }

    

  

 

  

    

    

支持拖拽的元素

    

    

    

    

需要开启拖拽的元素

    

      

      

      

      

    

    

展示框

    

  

 

<scripttype="text/javascript">

   

  // 定义全局变量 保存 拖放元素

  var moveDom ;

   

  // 让元素 能够被 拖放的内容 丢进去

  document.querySelector('.showBox').ondragover = function (e){

    //防止浏览器默认行为(W3C)

    e.preventDefault();

  }

   

  // 拖放元素 丢到 容器内 会触发 ondrop事件

  // 如果没有在 ondragover中 阻止默认行为 那么 无法触发 ondrop事件

  document.querySelector('.showBox').ondrop = function (){

    //console.log(moveDom);

    if(moveDom.src){

      // 如果 src有值 那么设置src属性

      // 获取 moveDom的src属性 并赋值给 盒子即可

    this.style.background = 'url('+moveDom.src+')no-repeat center/cover';

    }else{

      // 如果src没有值 那么 设置背景颜色

//      console.log(moveDom);

//      console.log(moveDom.style.backgroundColor);

      // 该方法 返回的内容是 style属性

      // getComputedStyle 能够获取 style标签中 写的样式

      console.log(window.getComputedStyle(moveDom).backgroundColor);

      this.style.backgroundColor = window.getComputedStyle(moveDom).backgroundColor;

    }

  }

   

  // 当我们开始拖放元素的时候 会触发 ondragstart事件

  var imgs = document.querySelectorAll('img');

  for (var i=0;i

    imgs[i].ondragstart=function(){

      moveDom=this;

    }

  }

   

   

  // 为div绑定拖拽开始事件

  varcolorBoxs=document.querySelectorAll('.colorBox');

  for (vari=0;i

    colorBoxs[i].ondragstart=function(){

      moveDom=this;

    }

  }

</script>

 

json|js css3实现图片拖拽效果

http://m.bbyears.com/css/128131.html

推荐访问:json格式化 json在线格式化 js格式化 js刷新当前页面 jsp js保留两位小数
相关阅读 猜你喜欢
本类排行 本类最新