jquery center image after zooming in overflow:auto container
I need help centering an image inside a container with overflow:auto after enlarging the image width and height.
live demo: http://jsfiddle.net/RCw4T/1
The underlying idea is that when the user centers a section开发者_如何学编程 of the image inside the container and clicks zoom, the image enlarges but still remains centered on that section. that way you can continue zooming in on a section without having to hunt for the section after every click.
looks the script prevents giving top
and left
values for less than 0, if you change the logic to allow values < 0 you should get a centered zoom...
Change this
iTop = (iNewH < ipH ? (ipH / 2) - (iNewH / 2) : 0);
iLeft = (iNewW < ipW ? (ipW / 2) - (iNewW / 2) : 0);
To this
iTop = (ipH / 2) - (iNewH / 2);
iLeft = (ipW / 2) - (iNewW / 2);
EDIT:
to allow scrolling to all parts of the image (ie no negative positioning) you can use the ScrollTo jquery plugin
example fiddle
something like
if (iNewH > $container.height() || iNewW > $container.width()) {
$container.scrollTo({
top:(iNewH - $container.height()) / 2,
left:(iNewW - $container.width()) / 2
});
}
might consider changing the above logic to handle height/width separately, I'll leave that to you.
Here is a fiddle: http://jsfiddle.net/maniator/jhDhM/
It might need some tweaking.
Here is the js code in the fiddle:
var zoomFactor = 1;
$('#container img').click(function(e) {
var iScaler = 1.5,
iH = $(this).height(),
iW = $(this).width(),
iNewH = iH * iScaler,
iNewW = iW * iScaler,
$parent = $(this).parent(),
zoomPosX = (e.clientX - ($parent.width() / 2)) / zoomFactor,
zoomPosY = (e.clientY - ($parent.height() / 2)) / zoomFactor;
zoomFactor *= iScaler;
$(this).css({
top: zoomPosY + 'px',
left: zoomPosX + 'px',
width: iNewW + 'px',
height: iNewH + 'px'
});
});
In your version: http://jsfiddle.net/maniator/RCw4T/10/
That fixes the less than greater than mix up and you should go right centered all of the time :-)
精彩评论