最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Drag and Drop along a diagonal line? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Oct 30, 2009 at 2:46 James Black 41.8k10 gold badges92 silver badges170 bronze badges asked Oct 30, 2009 at 2:36 Jason HallJason Hall 20.9k4 gold badges52 silver badges57 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

plete 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)

  1. 暂无评论