开发者

Drag and Drop along a diagonal line?

Are there any examples of a drag-and-drop solution in which the elements being dragged can only move along a slanted line? For example, constrain an element's draggability so that it can only be moved along a 30º line, or 10º, etc.

Most examples I've been able to find only constrain the dragged element's area to either a vertical or horizontal line, or to within a larger parent div.

Possibly related: Drag along a diagonal line no further than 100px, 开发者_开发知识库or along a curve.


complete example (FF only)

<div id="drag" style="position:absolute;width:20px;height:20px;background:red"></div>
<script>
var angle = 10;
window.onload = function() 
{
    var d = document.getElementById("drag");
    d.onmousedown = function() {
        document.onmouseup = function() {
            document.onmousemove = null;
        }
        document.onmousemove = function(e) {
            d.style.left = e.clientX;
            d.style.top = e.clientX * Math.tan(angle * Math.PI / 180);
        }
    }
}
</script>


It would seem the only way to really do that, without really annoying the user, is to keep track of the angle from the starting location, and if they are in an invalid angle then don't set the droptarget.

This way, if they let go it reverts back to the original position, and the only valid places to drop meet your requirements.


This seems easy to do if you've written your own DnD handler. Basically, DnD movement that is constrained to either vertical or horizontal axises work by only changing the left or top CSS attributes when dynamically position the draggable element.

You can use this same idea to customize this restrained behavior. Instead just translating the (X,Y) of the current mouse position for the element's CSS left/right, you can use the X for the left and derive the right by passing it through a linear function like y = mx + b.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜