首页 > 解决方案 > 如何 VANILLA 在 MOBILE 上拖放

问题描述

我在这里有一些代码:https ://codepen.io/anon/pen/PrZqqR

我想做的是在 < 720 px 的屏幕上实现拖放行为

我如何知道我要拖动的框应该position: relative用于此目的,所以我需要在最后指定我的移动功能。只欢迎香草 JS。谢谢!

else if (window.innerWidth <= 720) {
    for (var i = 0; i < images.length; i++) {
        images[i].addEventListener('touchstart', touchstart);
        images[i].addEventListener('touchend', touchend);

    }
}

function touchstart() {
    window.startTime = new Date();
}

function touchend() {
    window.endTime = new Date();
    if (window.endTime - window.startTime < 1000) {
        // just show preview as time is < 1 sec
        // url for the img src
        let url = "url(" + this.childNodes[1].getAttribute("src") + ")";
        // hide preview text
        document.querySelector(".alert").style.display = "none";
        // set preview image
        target.style.backgroundImage = url;
        target.classList.add("back_set");

        // end of simple click event
    } else {
        // this section handels the dragging story
        // add shake and start dragging, time is > 1 sec
        console.log("more than 1 sec");
        // make draggable
        this.setAttribute("draggable", "true");
        this.style.position = "absolute";
        // make shake animation
        this.style.animation = "shake 1s infinite";
        var x = parseInt(this.style.left);
        var y = parseInt(this.style.top);
        this.addEventListener("touchmove", move);
    }
}

function move() {
    console.log("moving");
}

标签: javascriptdrag-and-drop

解决方案


这样,您可以通过触摸拖动元素并收集其 id 和最终位置。它实际上对我有用。

HTML:

<!-- Div element you want to drag with touch -->
<div class="draggable" id="_draggable">                    
</div>

JavaScript:

let box = document.querySelector(".draggable");


box.addEventListener('touchmove', (e) => {
    //Gets movement in px of the touch movement
    let touchLocation = e.targetTouches[0];
    //Gets element data
    currentElement = e.target;
    //Gets element id
    currentElementId = currentElement.id;

    //Moves element
    box.style.left = touchLocation.pageX + 'px';
    box.style.top = touchLocation.pageY + 'px';
})



box.addEventListener('touchend', (e) => {
    //Picks up the id of the dragged element
    console.log(currentElementId)

    //Picks up the new element position
    let x = parseInt(box.style.left);
    let y = parseInt(box.style.top);

})

记住拖动元素必须有position: absolute;position: relative;

如果您需要其他任何东西,请告诉我。


推荐阅读