21.拖拽事件

拖拽事件

html部分

css部分

*{
    margin: 0;
    padding: 0;
}

body{
    display: flex;
    height: 100vh;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    background-color: steelblue;
}

.container{
    display: flex;
}

.empty{
    width: 150px;
    height: 150px;
    border: 3px solid black;
    background-color: white;
    margin: 10px;
}
.fill{
    background-image: url('./static/20180529205331_yhGyf.jpeg');
    cursor: pointer;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover
}
.hovered{
    background-color: #333;
    border-color: white;
    border-style: dashed;
}

js部分

// 获取dom
const fill = document.querySelector(".fill");
let empty = document.querySelectorAll(".empty");

empty.forEach(function (item) {
    item.addEventListener("dragstart", dragstart)
    item.addEventListener("dragend", dragend)
    item.addEventListener("dragover", dragover)
    item.addEventListener("dragenter", dragenter)
    item.addEventListener("dragleave", dragleave)
    item.addEventListener("drop", drop)
})
// 是否有拖拽元素
let is_start = false

// 拖拽经过
function dragover(e) {
    if (is_start) {
        e.preventDefault()
    }
}

// 拖拽进入
function dragenter(e) {
    if (is_start) {
        this.classList.add("hovered")
        this.classList.add("fill")
    }
}

// 拖拽离开
function dragleave(e) {
    if (is_start) {
        this.className = "empty";
    }
}

// 拖拽结束 
function drop(e) {
    if (is_start) {
        this.className = "empty fill";
        this.setAttribute("draggable", true)
    }
    
}

// 本次拖拽开始,判断当前拖拽元素是否有图片
function dragstart(e) {
    if (this.className.indexOf("fill") != -1) {
        is_start = true
    }
}
// 本次拖拽结束
function dragend(e) {   
    if (is_start) {

        // 拖拽数组转换为真数组
        empty=Array.from(empty)

        // 如果超出拖拽区域,图片复原
        const res=empty.find((item)=>item.className.indexOf("fill") != -1)
        if(res){
            this.className = "empty";
            this.setAttribute("draggable", false)
        }else{
            this.className = "empty fill"
        }

        is_start = false
        
    }
}

效果

21.拖拽事件_第1张图片

你可能感兴趣的:(前端开发50个案例,前端,javascript)