javascript - 如何 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");
}
解决方案
这样,您可以通过触摸拖动元素并收集其 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;
如果您需要其他任何东西,请告诉我。
推荐阅读
- sql - 选择字段与多个预定义值相关联的行
- angular - list.map 如何等待请求响应?
- r - R中的字符串检测
- javascript - 将单个模型值(字符串)作为参数传递给可重用的 javascript 函数以在 MVC 视图中设置表格单元格类
- python - 按两个字段对 2D 列表进行排序
- mysql - 如何结合sql查询?
- mongodb - 在 MongoDB 中使用按位或
- c# - C# 从较小的数组生成随机二维数组时遇到问题
- javascript - 带有 webpack 的 Simditor
- java - 在 IntelliJ 或任何其他 IDE 中,是否可以以某种方式显示/链接本机方法调用的来源?