最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
js css3实现图片拖拽效果
时间:2017-05-22 编辑:简简单单 来源:一聚教程网
代码如下 | 复制代码 |
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; }
支持拖拽的元素
需要开启拖拽的元素
展示框
// 定义全局变量 保存 拖放元素 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; } } |
相关文章
- HTML简单购物数量小程序代码展示 10-31
- html canvas实现弹幕功能 10-31
- HTML中空格表示的意义 10-31
- html area标签解读 10-31
- html使用表单标签实现注册页面代码展示 10-31
- 使用HTML截图并保存为本地图片的代码展示 10-31