简体   繁体   中英

Center draggable div relative to cursor when the size of the div changes

I'm writing an application with draggable fields (the divs). Before these fields are placed they are one size but then once they are picked up and being dragged they change to their "final" size (the size can change at a later time too, but they stay the dragged size until it's changed manually later).

What I'm trying to do is center the div relative to the cursor when the div is being dragged.

I know about the cursorAt property of draggable objects, but it's not working when you drag the object for the first time. If you drag, drop, and drag again it will center correctly.

Fiddle demonstrating the issue.

$('div').draggable({
    start: function () {
        $(this)
            .css('height', (Math.floor((Math.random() * 250) + 100).toString() + 'px'))
            .css('width', (Math.floor((Math.random() * 250) + 100).toString() + 'px'));

        $(this).draggable('option', 'cursorAt', {
            top: parseInt($(this).css('height')) / 2,
            left: parseInt($(this).css('width')) / 2
        });
    }
});

Obviously that's just an example, but it demonstrates the point because it will never center the div relative to the cursor. I figured that since I'm setting the CSS first that it should be doing it correctly, but it doesn't.

I've also tried moving the changing of the size to the mousedown event in to make sure the CSS get's changed first (in case for some reason it wasn't...was just a way to make sure) but it still doesn't work correctly.

And I also tried calculating the new sizes first, and then using the variable to do the calculations instead of relying on the CSS values. Still didn't work.

Do you have to use the .draggable() from jQuery UI ?
I put together a jQuery plugin at http://pastebin.com/vCr0xuTz which auto centers like you need
You can then just use $('div').drag(); and that should center the div when the size changes.

JSFiddle: http://jsfiddle.net/blue11086/d06r990w/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM