简体   繁体   中英

center a draggable growing div

I have a div which could be dragged around and scaled. It may or may not be larger than the window, I am trying to write a function which will keep it centered around its current center relative to the window when the div's width or height is changed (by a scaling function). To do this I will need to change its top and left (or its margin but prefer top and left position) to a number which relates to its current top and left position. I just can't wrap my head around the logic of the function which will keep it centered at its current position. To center it completely I would just change its top and left to (-)half of the size of the div, but to keep it centered around its current center what would i do!

Depending on how you increasing the size of the div width/height, you can just change the margin of the div to reflect a fraction of the change in size. You could also look into changing the left/top absolute values in a similar way.

For example, with jQuery animate:

$("#draggable").animate({
    height: '+=60',
    width: '+=60',
    marginLeft: '-=30',
    marginTop: '-=30'
},1000);

Example:

http://jsbin.com/ikabih/2/edit

Got it with help from a friend..

function changeZoom(amount)
{   
    var oldWidth = $('#zoom').width(), oldHeight = $('#zoom').height();
    if(oldWidth == amount){return false}
    var xPercent = (($('#viewer').width() / 2) + Math.abs($('#zoom').position().left)) / oldWidth,
    yPercent = (($('#viewer').height() / 2) + Math.abs($('#zoom').position().top)) / oldHeight;

    var newLeft = (amount * xPercent) - ($('#viewer').width() / 2),
    newTop = (amount * yPercent) - ($('#viewer').height() / 2);

    newLeft = 0 - newLeft;
    newTop = 0 - newTop;

}

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