jQuery drag and draw

后端 未结 2 1634
迷失自我
迷失自我 2021-02-02 12:21

I\'m trying to build a jQuery plugin that allows you to drag and draw a rectangle (or a div with a border) but I\'m not sure how to do it. I don\'t know of any that currently ha

2条回答
  •  醉话见心
    2021-02-02 13:08

    $("#YOUR_ELEMENT_ID").on("mousedown", function (e) {
        var click_x = e.pageX;
        var click_y = e.pageY;
    
        /* Posição do objeto */
        var x = parseFloat($(this).css("left").replace("px", "")),
            y = parseFloat($(this).css("top").replace("px", ""));
        /* Calcula distância no eixo x */
        var distanc_x = Math.abs(x - click_x);
        var distanc_y = Math.abs(y - click_y);
    
        $("#YOUR_ELEMENT_ID")
            .on("mousemove", function (e) {
    
                var new_x = e.pageX - distanc_x;
                var new_y = e.pageY - distanc_y;
    
                $(this).css({
                    top: new_y,
                    left: new_x,
                });
    
            }).on("mouseup", function (e) {
            $(this).off("mousemove");
        });
    
    });
    

提交回复
热议问题