我有一个我希望能够拖动的元素,但我内部的元素是我不想拖动的。我希望在没有(很多)jQuery的情况下有一个简单的答案。
这是我想要实现的目标。
<html>
<head>
</head>
<style>
.a {
width:400px;
height:400px;
border:1px solid black;
}
.b{
width:200px;
height:200px;
border:1px solid black;
margin:20px;
}
</style>
<body>
<div class="a" draggable="true">
<span>I can drag this!</span>
<div class="b" draggable="false">
I can drag this as well, but I don't want to.
</div>
</div>
</body>
</html>
http://plnkr.co/edit/Xto7lPO32TRVScewJkS9
有什么想法吗?
答案 0 :(得分:3)
不知道这个问题是否仍然相关,但我找到了解决问题的方法:
<body>
<div class="a" draggable="true">
<span>I can drag this!</span>
<div class="b" draggable="true" ondragstart="event.preventDefault()">
I can drag this as well, but I don't want to.
</div>
</div>
</body>
看起来有点hacky,但它确实可以解决问题。我还没有找到任何其他方法来解决这个问题。希望它可以帮到你。
干杯 萨姆
答案 1 :(得分:0)
您想要做的是在此代码中可以使用(也允许用手指触摸):
var draggables = document.querySelectorAll('.is-draggable');
[].forEach.call(draggables, function (el) {
var startX, startY, initialX, initialY,
auth = function (target) {
var notDraggables = el.querySelectorAll('.is-not-draggable');
return [].filter.call(notDraggables, function (element) {
return target !== element;
}).length > 0;
};
function move(gesture) {
var deltaGestureX = gesture.clientX - initialX,
deltaGestureY = gesture.clientY - initialY,
deltaPositionX = startX + deltaGestureX,
deltaPositionY = startY + deltaGestureY,
limitX = parseInt(window.innerWidth - el.clientWidth, 10),
limitY = parseInt(window.innerHeight - el.clientHeight, 10);
if (deltaPositionY <= 0) {
el.style.top = '0px';
} else if (deltaPositionY >= limitY) {
el.style.top = limitY + 'px';
} else {
el.style.top = startY + deltaGestureY + 'px';
}
if (deltaPositionX <= 0) {
el.style.left = '0px';
} else if (deltaPositionX >= limitX) {
el.style.left = limitX + 'px';
} else {
el.style.left = startX + deltaGestureX + 'px';
}
return false;
}
function mousemove(e) {
move(e);
}
function mouseup() {
document.removeEventListener('mousemove', mousemove);
document.removeEventListener('mouseup', mouseup);
}
function touchmove(e) {
move(e.touches[0]);
}
function touchend() {
document.removeEventListener('touchmove', touchmove);
document.removeEventListener('touchend', touchend);
}
el.addEventListener('touchstart', function (e) {
if (auth(e.target)) {
startX = el.offsetLeft;
startY = el.offsetTop;
initialX = e.touches[0].clientX;
initialY = e.touches[0].clientY;
document.addEventListener('touchmove', touchmove);
document.addEventListener('touchend', touchend);
}
});
el.addEventListener('mousedown', function (e) {
if (auth(e.target)) {
startX = el.offsetLeft;
startY = el.offsetTop;
initialX = e.clientX;
initialY = e.clientY;
document.addEventListener('mousemove', mousemove);
document.addEventListener('mouseup', mouseup);
return false;
}
});
});